简体   繁体   中英

Observable Array *ngFor directive Angular

I'm stuck with "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I'm trying to set up a Basket store to provide data to my BasketPage.

In my service i got :

nourritureArrayTest: Nourriture[] = [];
getNourriturePanier(): Observable<Nourriture[]> {
  return of(this.nourritureArrayTest)
}

in my Basket Page ts :

nourriturePanierTest: Observable<Nourriture[]>
ngOnInit() {
  this.nourriturePanierTest= this.panierService.getNourriturePanier()
}

nourritureArrayTest is an array of object of type

in my Basket.html

<div *ngFor="let extra of nourriturePanierTest | async">
<p>{{extra.name}}</p></div>

nourriturePanierTest is an observable. You need to store this observable in some array and then use that array inside an ngFor.

ngFor only works on Array.

I've added some code for your help.

nourriturePanierTest: Nourriture[];
ngOnInit() {
this.nourriturePanierTest= this.panierService.getNourriturePanier().subscribe(res=>{
this.nourriturePanierTest= res })
}

You have to subscribe to the observable instead of assigning it to a variable:

ngOnInit() {
  this.panierService.getNourriturePanier().subscribe(res=>{
    this.nourriturePanierTest= res
  })
}

and it will work if this.nourritureArrayTest is an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM