【问题标题】:how can i use async pipe when I'm using graphql queries?使用 graphql 查询时如何使用异步管道?
【发布时间】:2021-09-16 09:12:59
【问题描述】:

我有一个 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
});
}

现在,我该如何避免这个错误?

【问题讨论】:

    标签: angular graphql subscription apollo-angular async-pipe


    【解决方案1】:

    你不需要使用async管道,我认为你需要使用安全导航运算符。

    把它放在你的 HTML 中(添加问号):

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

    基本保证数据存在,那么文章在数据里面,图片在文章里面。

    详细了解安全导航操作员here

    有一种方法可以使用 async 管道,但我看到你 subscribe 到 observable 并且你设置了 dataloadingerrors 的值,这将涉及更多的工作来获得这些async 管道的属性。

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 2023-03-29
      • 2020-03-02
      • 2021-04-19
      • 2019-11-25
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      相关资源
      最近更新 更多