【发布时间】:2017-05-25 00:17:05
【问题描述】:
您好,我需要帮助我创建了一个角度服务,但是当我想从我的 json 文件中查看数据时,它显示了这个错误,我尝试了很多不成功的解决方案
app.component.ts
import {Component, OnInit} from '@angular/core';
import {Car} from './domain/car';
import {CarService} from './service/carservice';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [CarService]
})
export class AppComponent implements OnInit {
cars1: Car[];
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getCarsSmall().subscribe(cars => this.cars1 = cars);
}
}
汽车服务.ts
@Injectable()
export class CarService {
private jsonUrl = './cars-smalll.json';
constructor(private http: Http) {}
getCarsSmall(): Observable<Car[]> {
return this.http.get(this.jsonUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
汽车-smalll.json
[
{
"brand": "VW",
"year": 2012,
"color": "Orange",
"vin": "dsad231ff"
},
{
"brand": "Audi",
"year": 2011,
"color": "Black",
"vin": "gwregre345"
},
{
"brand": "Renault",
"year": 2005,
"color": "Gray",
"vin": "h354htr"
}
]
提前谢谢你。
【问题讨论】:
-
此错误几乎总是是由服务器配置问题引起的,而不是由 Angular 引起的。服务器正在发送一个 HTML 文档,而不是您的一个 javascript 文件。你这里用的是什么服务器,你的服务器的路由配置是什么样的?
-
或模拟 JSON 路径不正确,您在浏览器的网络日志中看到了什么?
-
感谢 Claies 的回复,所以在我的情况下,我想使用存储在相同结构中的 json 文件(src/app/data/cars-smalll.json)
-
在assets下添加Json文件然后运行
-
我尝试将 json 放在 assets 文件夹中,并将 json 的路径更改为 (/src/app/assets/cars-smalll.json) 但我得到了同样的错误
标签: json angular http observable