I have an angular project and in my component, I fetch data with graphql and in HTML I show an image of the result. but for a moment, I get this error in the console:
ERROR TypeError: Cannot read property 'image' of undefined
this is my html code:
<div
[style.background-image]="
'url(http://localhost:1337' + (data.article.image.url )+ ')'
"
>
</div>
and in my component i have:
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
});
}
now, how can I avoid this error?
You don't need to use the async
pipe, I think you need to use the safe navigation operator.
Put this in your HTML (add the question marks):
<div
[style.background-image]="
'url(http://localhost:1337' + (data?.article?.image?.url )+ ')'
"
>
</div>
It will basically ensure that data exists, then article exists inside of data and that image exists inside of article.
Learn more about the safe navigation operator here.
There is a way to use the async
pipe but I see you subscribe
to the observable and you set values for data
, loading
, and errors
and it will involve more work to get those properties with the async
pipe.