我試圖顯示一個列表,其中包含從本地json文件中獲取的數據。以下是我的服務看起來如何。如何在Angular 2+中獲取json數據
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');
}
}
這裏是類別菜單組件在那裏我注入它的外觀至今
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
);
}
}
現在,我在控制檯中得到的錯誤是404。對於此項目,我使用CLI版本1.0和src/api/categories.json文件夾內的categories.json文件。
我在做什麼錯在這裏?
你怎麼張貼代碼塊具有上「運行代碼片斷」功能? – stardiviner