简体   繁体   English

可观察数组* ngFor指令Angular

[英]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." 我陷入“错误错误:找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到Iterables,例如数组。”

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 : 在我的购物篮页面ts中:

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

nourritureArrayTest is an array of object of type nourritureArrayTest是类型为Object的数组

in my Basket.html 在我的Basket.html中

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

nourriturePanierTest is an observable. nourriturePanierTest是可观察的。 You need to store this observable in some array and then use that array inside an ngFor. 您需要将此可观察对象存储在某个数组中,然后在ngFor中使用该数组。

ngFor only works on Array. ngFor仅适用于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 如果this.nourritureArrayTest是一个数组,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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