我正在尝试通过服务读取json文件数据。我在名为product.json的assets文件夹中创建了该文件。 但是在运行代码时,它会在控制台中返回“http://localhost:4200/assets/product.json 404(Not Found)”。
这是我的服务文件代码:
import { Injectable } from '@angular/core';
import { Http,Response,Headers,RequestOptions } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class ProductDataService {
headers:Headers;
options:RequestOptions;
//url:string="/localservice/product.json";
url:string = "assets/product.json"
constructor(private _http:Http) {
this.headers = new Headers({'Content-type':'application/json','Accept':'q=0.8;application/json;q=0.9'});
this.options =new RequestOptions({headers:this.headers})
}
getAllProduct(){
return this._http.get('../assets/product.json',this.options)
.map((res:Response)=>res.json());
}
}
我尝试使用“assets / product.json”,“.. / assets / product.json”作为路径
porduct.component.ts:
export class ProductComponent {
allProduct:Product[]=[];
constructor(private _data:ProductDataService) { }
ngOnInit() {
/* this._data.getAllProduct().subscribe(
(data:Product[])=>{
this.allProduct=data;
}
); */
}
onClick(value:string){
if(value!=''){
this.allProduct=this.allProduct.filter(res=>res.pname.startsWith(value));
}
else{
this._data.getAllProduct().subscribe(
(data:Product[])=>{
this.allProduct=data;
}
);
}
}
}
角cli.json:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "new-app"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
请告诉我问题在哪里。谢谢提前
答案 0 :(得分:0)
试试这样:
使用this._http.get('assets/product.json',this.options)
之类的路径代替this._http.get('../assets/product.json',this.options)
getAllProduct() {
return this._http.get('assets/product.json', this.options)
.map((res: Response) => res.json());
}
答案 1 :(得分:0)
尝试下面的代码
import {Injectable} from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProductDataService {
private data: any;
constructor(private http: Http) { }
getData(){
this.http.get('assets/data/products.json')
.map((res) => res.json())
.subscribe(data => {
this.data = data;
}, (rej) => {
console.error("Could not load local data",rej)
});
}
}
将../assets/data/products.json
更改为assets/data/products.json