使用 graphql 查询时如何使用异步管道?

问题描述

我有一个 angular 项目,在我的组件中,我使用 graphql 获取数据,并在 HTML 中显示结果的图像。但有一段时间,我在控制台中收到此错误

ERROR TypeError: Cannot read property 'image' of undefined

这是我的 html 代码

<div
[style.background-image]="
'url(http://localhost:1337' + (data.article.image.url )+ ')'
"
>
</div>

在我的组件中,我有

ngOnInit(): void {
this.queryArticle = this.apollo
.watchQuery({
  query: ARTICLE_QUERY,variables: {
    id: this.route.snapshot.paramMap.get("id")
  }
}).valueChanges.subscribe(result => {
  this.data = result.data;
  this.loading = result.loading;
  this.errors = result.errors
});
}

现在,我怎样才能避免这个错误

解决方法

您不需要使用 async 管道,我认为您需要使用安全导航操作符。

将其放入 HTML 中(添加问号):

<div
[style.background-image]="
'url(http://localhost:1337' + (data?.article?.image?.url )+ ')'
"
>
</div>

它基本上会保证数据存在,然后文章存在于数据中,图像存在于文章中。

了解有关安全导航运算符 here 的更多信息。

有一种方法可以使用 async 管道,但我看到您 subscribe 到可观察对象,并且您为 dataloading 和 {{1} 设置了值使用 errors 管道获取这些属性需要做更多工作。