Reputation: 718
What is the best way to access the data from an observable stream when I need to access it in an Angular component? I'm aware I can use an async pipe in the template but I need to access the data in the actual component.
So far I've extracted the data to a new variable with either a tap or subscribe but I'm just curious if I'm missing an easier or more concise way to do it. If not, is there a preferred method between tap and subscribe?
//assume db.getBook() returns an observable with a book object
this.subscription = db.getBook("153").pipe(
tap(book => this.book = book).subscribe()
//or
this.subscription = db.getBook("153").subscribe(book => this.book = book)
Upvotes: 1
Views: 1896
Reputation: 38094
The .pipe
method is used to chain observable operators and you will always get your emitted data. In addition, pipe method allows webpack to drop unused operators from the final JavaScript bundle. It makes it easier to build smaller files.
.tap
transparently performs actions or side-effects, such as logging. It does not modify the stream.
.subscribe
will be called just one time and is used to subscribe to observable response. Moreover, we can put response into some variable to display it into the view.
It is better to use async
pipe for template:
<option *ngFor="let item of items$ | async">
{{ item?.name }}
</option>
For assigning data from the backend, you can use subscribe()
method:
this.yourService.getYourData()
.subscribe(val =>
this.items = val
);
The comment of source code of tap()
method says:
This operator is useful for debugging your Observables for the correct values or performing other side effects.
Note: this is different to a
subscribe
on the Observable. If the Observable returned bytap
is not subscribed, the side effects specified by the Observer will never happen.tap
therefore simply spies on existing execution, it does not trigger an execution to happen likesubscribe
does.
So it is better to use subscribe
method to assign data because:
tap
methodtap
is not subscribed, the side effects
specified by the Observer will never happen. So in any way, you need to call subscribe
method. So there is no need to use tap
method if you want just assign dataUpvotes: 2