【问题标题】:Trying to render JSON in HTML in Angular2尝试在 Angular2 中以 HTML 格式呈现 JSON
【发布时间】: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


【解决方案1】:

由于你的currentStore对象是异步接收的,你可以像这样使用“elvis”操作符

{{ currentStore?.Name }}

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

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

【讨论】:

  • 感谢听起来像是一个方便的操作员来做检查。
  • @MrNew 当您在 angular2 中处理异步操作时,它确实让您的生活更轻松 :-)
  • 嗨,关于这个我知道它的老问题还有一个问题。现在它显示了 storeName,不知何故它并不总是更新 {{ currentStore?.Name }},有时我必须刷新页面才能更新。
  • @MrNew 嗯,没有看到用例就什么也说不出来。也许您在控制台中遇到错误?你能创建一个新的问题来阐述这个问题吗?
  • 我创建了一个关于它的新问题stackoverflow.com/questions/41818222/…
猜你喜欢
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多