【发布时间】:2017-01-18 11:09:32
【问题描述】:
我正在尝试将从后端返回的 JSON 呈现为 HTML {{ object.x }},我在我的共享服务中使用 BehaviourSubject,我在其中调用了我正在尝试呈现的列表的 API 端点。
public storesChanged = new BehaviorSubject([]);
public getStores(): void {
this.retrieveResults().subscribe((results) => {
this.storesChanged.next(results.Results)
console.log('Name >> ', results.Results[0].Name) // this shows me the Name
});
}
public retrieveResults(): Observable<any> {
return this.http.get('/api/Stores/Summary')
.map(res => res.json())
}
使用此服务:
this.sharedService.storesChanged.subscribe((res) => {
this.currentStore = res.find((x) => x.Id === this.storeId)
// this returns the object based on the Id which should be able to use in my HTML
})
这是我试图在 HTML {{ currentStore.Name }} 中呈现的对象,但它返回错误 Cannot read property 'Name' of undefined。
{
'Id': 1,
'Name': 'Eastleigh'
}
我很困惑为什么当属性在对象中时它返回'Name' of undefined。谁能指出原因。
【问题讨论】:
-
{{ currentSore.Name }}->{{ currentStore.Name }}你打错字了 -
是的,抱歉,这是我在输入这个问题时自己的错字
-
你试过猫王算子吗?
{{ currentStore?.Name }} -
@echonax 有什么用,但不确定 elvis 运算符是什么?介意稍微解释一下吗?
-
Elvis 操作员防范“未找到属性”。如果 currentStore 上不存在“name”,它将停止尝试评估它(以及任何其他跟随它的道具),从而使您免于可怕的错误。这样,当“名称”最终可用时,您将得到您所期望的。
标签: javascript json angular