Reputation: 115
I'm newbie in Angular 8 and I'm trying to implement a service to get the data in JSON
format loaded into an API
but I've got the following error on the console
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
I've also been reading similar questions for this error but I'm haven't been able to solve it
Here's my .ts code where I make the service call
@Injectable({
providedIn : 'root'
})
export class CarsService {
private CarURL = 'https://catalogo-autos.herokuapp.com/api/autos';
constructor(private http: HttpClient) { }
getCars(): Observable<Car[]>{
return this.http.get<Car[]>(this.CarURL);
}
}
And here is the service:
ngOnInit() {
this.getCars();
}
getCars(): void {
this.carService.getCars().subscribe((carsTemp)=>{
this.cars = carsTemp;
})
}
Finally heres my HTML
markup
<ng-container *ngFor="let car of cars">
<div class="cars">
<div class="fas fa-eye" (click)="onSelect(car,infAuto)"></div>
<div>{{car.description}} </div>
</div>
</ng-container>
I'll appreciate any further help
Upvotes: 0
Views: 87
Reputation: 31105
Loading the API, it looks like the required cars array is actually within data
property.
You could map the result to the data
property before returning the observable to the controller. Try the following
Service
@Injectable({
providedIn : 'root'
})
export class CarsService {
private CarURL = 'https://catalogo-autos.herokuapp.com/api/autos';
constructor(private http: HttpClient) { }
getCars(): Observable<Car[]>{
return this.http.get<Car[]>(this.CarURL).pipe(map(response => response.data));
}
}
Upvotes: 2
Reputation: 428
You have to access to data
property of response you get. The object, you are getting isn't array. It is object with some extra data, which one of the field data
is actually your required property. You have to remember, that after compiling your typescript code, you are getting js and respone is parsed via JSON.parse
(be aware when some of fields are f.e. type of Date
)
Upvotes: 2