我有一个界面:
export interface ItemResponse {
get: Array<Item>;
sent: Array<Item>;
}
我在组件中有一些代码:
itemData: ItemResponse;
ngOnInit() {
this.getItems();
}
getItems(){
this.itemService.getAllItem().subscribe(data => {
this.itemData = data;
});
}
模板部分:
<item-table [data]="itemData.get"></item-table>
我需要多次使用 Angular Material 表,因此我为此创建了一个组件。 A 想要传递数据源,但我收到下一个错误:
ItemComponent.html:5 ERROR TypeError: Cannot read property 'get' of undefined
at Object.eval [as updateDirectives] (ItemComponent.html:11)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:30537)
at checkAndUpdateView (core.js:29933)
at callViewAction (core.js:30174)
at execComponentViewsAction (core.js:30116)
at checkAndUpdateView (core.js:29939)
at callViewAction (core.js:30174)
at execEmbeddedViewsAction (core.js:30137)
at checkAndUpdateView (core.js:29934)
at callViewAction (core.js:30174)
我应该如何申报这个属性(property)?我尝试了很多方法,例如:
itemData = {get: [], sent:[]} as ItemResponse;
在本例中,itemData.get
并非未定义,但它是空的。
你知道我该怎么办吗?抱歉出现语法错误,英语不是我的母语。
最佳答案
您收到错误是因为 getItems()
执行异步操作,并且在订阅返回值之前 itemData
为 未定义
。
您需要使用 async pipe
或 bool 标志(例如isLoaded
)等待订阅完成。
对于async
管道,您可以执行以下操作:
getItems(){
this.itemData = this.itemService.getAllItem();
}
在模板中
<item-table [data]="(itemData | async).get"></item-table>
或者如果您想使用 bool 标志:
isLoaded = false;
getItems(){
this.itemService.getAllItem().subscribe(data => {
this.isLoaded = true;
this.itemData = data;
});
}
在模板中:
<item-table [data]="itemData.get" *ngIf="isLoaded"></item-table>
希望这有帮助
关于angular - 我应该如何在 Angular 中正确设置这个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58712407/