ngFor一个可观察的数组属性 [英] ngFor over an array property of an observable
问题描述
我有一个要在视图组件PersistedWaitlist中使用的对象:
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;
}
}
view组件注入了一个Observable持久化等待列表,我想显示其每个项目.为此,我具有以下组件:
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() {}
}
这是模板:
<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>
请注意此处的ngFor循环:我正在尝试访问等待列表对象的getItems()方法,但出现以下错误:
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
有人知道在模板中读取Observable属性的最佳方法吗?我考虑过的一种方法是在视图组件的构造函数中提取items数组,并在其中构造一个单独的Observable,但是我也不知道该怎么做.
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.
推荐答案
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()"
这篇关于ngFor一个可观察的数组属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!