【发布时间】:2018-05-25 19:15:36
【问题描述】:
我正在尝试通过服务读取 json 文件数据。我已在名为 product.json 的资产文件夹中创建了该文件。 但是在运行代码时,它会在控制台中返回“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”作为路径
产品.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;
}
);
}
}
}
angular-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": {}
}
}
请告诉我问题出在哪里。提前谢谢
【问题讨论】:
-
您的
assets文件夹在哪里,它应该在src内,cli-config应该在includes属性中拥有assets文件夹 -
能否请您也发布 .angular-cli 文件?
-
是的资产在 src 里面
-
index.html 文件中有
<base href="/">吗? -
是的
在那里