繁体   English   中英

尝试在 Angular2 中以 HTML 呈现 JSON

[英]Trying to render JSON in HTML in Angular2

我正在尝试将后端返回的 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 谁能指出原因。

由于您的currentStore对象是异步接收的,您可以像这样使用“elvis”运算符

{{ currentStore?.Name }}

“elvis”或安全导航操作员将检查您的对象是否为空/未定义。 当它被定义时,angular 将尝试访问您选择的属性(名称)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM