你好,我需要帮助。我创建了一个Angular服务,但是当我想查看我的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);
}
}
carservice.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);
}
}
cars-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"
}
]
thank you in advance.