ngFor over an array property of an observable [duplicate]

て烟熏妆下的殇ゞ 提交于 2020-01-06 05:37:05

问题


I have an object that I would like to use in a view component, PersistedWaitlist:

export class PersistedWaitlist extends Waitlist implements Identifiable     {

  private items: PersistedWaitlistItem[];

  constructor(public readonly id: number, 
    createdAt: Date,
    name: string) {
    super(createdAt, name);
    this.items = new Array();
  }

  addItem(waitlistItem: PersistedWaitlistItem) {
    this.items.push(waitlistItem);
  }

  getItems(): Array<PersistedWaitlistItem> {
    return this.items;
  }
}

The view component is injected with an Observable persisted waitlist, and I would like to display each of its items. To do so, I have the following component:

@Component({
  selector: 'app-waitlist',
  templateUrl: './waitlist.component.html',
  styleUrls: ['./waitlist.component.css']
})
export class WaitlistComponent implements OnInit {

  @Input()
  waitlist: Observable<PersistedWaitlist>

  constructor() {
  }

  ngOnInit() {}

}

And here is the template:

<div id = "waitlist-root">
  <div id="waitlist-container">
    <app-waitlist-item *ngFor="let item of (waitlist | async).getItems()" [item]="item"></app-waitlist-item>
  </div>
</div>

Note the ngFor loop here: I am trying to access getItems() method of the waitlist object, but I am getting the following error:

WaitlistComponent.html:3 ERROR TypeError: Cannot read property 'getItems' of undefined

Does anyone know of the best way of reading the property of an Observable in a template? One approach I have considered is extracting the items array in the view component's constructor and making a separate Observable out of it, but I am not sure how to do that either.


回答1:


Try adding a safe navigation operator ? since getItems could be null when you try to access it as you are making a call asynchronously.

 <app-waitlist-item *ngFor="let item of (waitlist | async)?.getItems()"


来源:https://stackoverflow.com/questions/51580880/ngfor-over-an-array-property-of-an-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!