首页 > 解决方案 > 正确显示可观察对象值

问题描述

嘿,所以我越来越多地开始使用 Angular,我现在正在做我的第一个项目,我通过我的服务方法从我的数据库中获取数据:

  getPost(postID: String) {
    this.postDocument = this.db.doc('posts/' + postID)
    return this.postDocument.valueChanges()
  }

我在我的组件中调用该方法

  ngOnInit() {
    this.currentPost = this.route.paramMap.pipe(
      switchMap((params: ParamMap) => this.fs.getPost(params.get('id')))
    )
  }

到目前为止这有效,但我真的不明白如何在我的 HTML 中显示数据?例如,这给我带来了即使正确显示的标题也是空的。

<div>
  post-read-page works!
  <h1 *ngIf="currentPost">{{ (currentPost | async).titel }}</h1>
</div>

提前致谢

确切的错误:ERROR TypeError: Cannot read property 'titel' of null

标签: angulartypescript

解决方案


问题是它currentPost也可以为空,因此您还需要正确处理模板中的空大小写,以免出现错误。正如评论中已经建议的那样,您可以使用安全导航运算符(?.) 来处理这个问题。

然后你的绑定看起来像这样:

<div>
  post-read-page works!
  <h1 *ngIf="currentPost">{{ (currentPost | async)?.titel }}</h1>
</div>

推荐阅读