Reputation: 75
Hi I need help I created an angular service but when I want to view the data from my json file it shows me this error, I tried a lot of unsuccessful solution
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.
Upvotes: 5
Views: 26244
Reputation: 73357
Besides using the correct path suggested in comments, your problem is that you are trying to extract data from something that does not exist. Take a look at your json, it's an array. But in your extractData
-function you are trying to extract data from an object data
, which is of course not present in your JSON. So change that function to:
private extractData(res: Response) {
let body = res.json();
// return just the response, or an empty array if there's no data
return body || [];
}
This should do it, as well as correcting the path of the JSON file.
Upvotes: 5