我正在尝试显示包含从本地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文件。
我在这里做错了什么?
答案 0 :(得分:2)
将您的api/categories.json
移至资源文件夹,然后将网址更改为
return this._http.get('/assets/api/categories.json')