I am just looking in to this example https://github.com/arjunyel/angular-apollo-example/blob/master/frontend/src/app/app.component.ts#L28
It has this code:
this.tweets = this.tweetsGQL
.watch()
.valueChanges.pipe(map(tweets => tweets.data));
Just wondering how the this.tweets
gets the value assigned? Is it something to do with .pipe(map())
can you give some details on that?
In angular to show data in a *ngFor we can take two aproachs:
Show an observable using async. generally we use a convention that an observable variable begins by $
<div *ngFor="let tweet of ($tweets | async)?.tweets">
....
</div>
//In this case we use
this.$tweets=this.tweetsGQL
.watch()
.valueChanges.pipe(map(res=> res.data));
Show an array
<div *ngFor="let tweet of tweets.tweets">
....
</div>
//In this case we must subscribe -and not equal the observable to anything
this.tweetsGQL
.watch()
.valueChanges.pipe(map(res=> res.data))
.subscribe(res=>this.tweets=res);
About "map(tweets=>twees.data)". The observable can return anything. In this case return an object like
{data:tweets:[....],otherProperty:value}
We can map (transform) the response so the observable only return the "property" data. Not the whole object
map(res=>res.data)
//the for must be over tweets.tweets *ngFor="let tweet of tweets.tweets"
even we can map the response so the observable return data.tweets
map(res=>res.data.tweets)
//the for must be over tweets *ngFor="let tweet of tweets"
NOTE:I change the response using the variable "res" to avoid confusions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With