angular - 正确显示可观察对象值
问题描述
嘿,所以我越来越多地开始使用 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
解决方案
问题是它currentPost
也可以为空,因此您还需要正确处理模板中的空大小写,以免出现错误。正如评论中已经建议的那样,您可以使用安全导航运算符(?.) 来处理这个问题。
然后你的绑定看起来像这样:
<div>
post-read-page works!
<h1 *ngIf="currentPost">{{ (currentPost | async)?.titel }}</h1>
</div>
推荐阅读
- model - 如何理解自动驾驶汽车的 pomdp 模型
- python - 使用 Python 制作全长定义的测试数据?
- python - AttributeError:模块“moviepy.audio.fx.all”没有属性“audio_fadein”
- javascript - 如何构建一个大于 nodeList 的数组,将空字符串作为缺失类的占位符?
- tomcat8 - Tomcat 中针对 HTTP 501 错误的自定义错误页面
- python - 如何在 Python 自定义字典中实现整数类型键的一致散列?
- c# - 从字典中选择文本 - 单个单词与短语 - 例如“大米”与“米酒”
- metrics - Istio egressgateway 不收集标签为“reporter=destination”的指标
- php - 如何使用自定义模块和 PHP 生成文件?
- python - 如何在 Tkinter 中为循环中创建的相同按钮提供唯一名称?