我有一个要在视图组件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持久化等待列表,我想显示其每个项目。为此,我具有以下组件:
@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()方法,但出现以下错误:
WaitlistComponent.html:3 ERROR TypeError: Cannot read property 'getItems' of undefined
有人知道在模板中读取Observable属性的最佳方法吗?我考虑过的一种方法是在视图组件的构造函数中提取items数组,并在其中构造一个单独的Observable,但是我也不知道该怎么做。
答案 0 :(得分:2)
请尝试添加 safe navigation operator
?
,因为在异步进行呼叫时尝试访问getItems时可能为null。< / p>
<app-waitlist-item *ngFor="let item of (waitlist | async)?.getItems()"