尝试在Angular2中以HTML格式呈现JSON

时间:2017-01-18 11:09:33

标签: javascript json angular

我正在尝试从后端向HTML {{ object.x }}呈现返回的JSON,我在我的共享服务中使用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。有人可以指出原因。

1 个答案:

答案 0 :(得分:1)

由于您的currentStore对象是异步接收的,因此您可以使用&#34; elvis&#34;像这样的运营商

{{ currentStore?.Name }}

&#34;埃尔维斯&#34;或安全导航操作员将检查您的对象是否为null / undefined。当它被定义时,angular将尝试访问您选择的属性(Name)。

来源:https://en.wikipedia.org/wiki/Safe_navigation_operator