Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of .pipe(map())

Tags:

angular

rxjs

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?

like image 307
sreginogemoh Avatar asked Nov 08 '22 01:11

sreginogemoh


1 Answers

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

like image 81
Eliseo Avatar answered Nov 15 '22 07:11

Eliseo