简体   繁体   中英

How to fetch json data in Angular 2+

I'm trying to display a list with data fetched from a local json file. Here is how my service looks so far.

category.service.ts

 import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; @Injectable() export class CategoryService { constructor(private _http: Http) { } getCategories() { return this._http.get('api/categories.json') .map((response: Response) => response.json()) .do(data => console.log('All; ' + JSON.stringify(data))) .catch(this.handleError); } private handleError(error: Response) { console.log(error); return Observable.throw(error.json().error || 'Server error'); } } 

here is how the Category Menu component where I inject it looks so far

 import { Component, OnInit } from '@angular/core'; import { CategoryService } from '../category.service'; @Component({ selector: 'app-category-menu', templateUrl: './category-menu.component.html', styleUrls: ['./category-menu.component.css'] }) export class CategoryMenuComponent implements OnInit { errorMessage: string; commerceName= `El baratón`; categoryName = `Bebidas`; categories: any = 'Not assigned yet'; hasMenu?= true; constructor(private _categoryService: CategoryService) { } ngOnInit() { return this._categoryService.getCategories() .subscribe( categories => this.categories = categories, error => this.errorMessage = error ); } } 

Now, the error I am getting in the console is a 404. For this project I have used the CLI version 1.0 and the categories.json file inside of the src/api/categories.json folder.

What am I doing wrong here?

将您的api/categories.json移到资产文件夹,然后将网址更改为

return this._http.get('/assets/api/categories.json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM