I know I can subscribe to an object of type Observable
if I need to extract a value from it, but what if I want to use operators from RxJs
to reach the same goal. Please see the following code
this.placeService.getPlace(paramMap.get('placeId')).pipe(
take(1),
tap(place => { console.log('Place: ' + place); this.place = place; }));
What is wrong? Why it does not work as expected (this.place
is equal to undefined
)?
You have to subscribe to observable.
this.placeService.getPlace(paramMap.get('placeId'))
.pipe(
take(1),
tap(place => { console.log('Place: ' + place); this.place = place;}))
.subscribe();
the same use without tap
this.placeService.getPlace(paramMap.get('placeId'))
.pipe(take(1))
.subscribe(place => { console.log('Place: ' + place); this.place = place;});
should I unsubscribe?
Take(1) takes only one value and do unsubscribe in backdrop
what about another case:
this.placeService.getPlace(paramMap.get('placeId')).subscribe(place => this.place = place);
Should I unsubscribe here?If you have hot observable you have to remember about unsubscribe. The best way to unsubscribe from hot observables is using the takeUntil rxjs operator.
You add in your component filed
private readonly destroy$: Subject<void> = new Subject()
and implement ngOndestroy method, in this method:this.destory$.next();this.destroy$.complete()
and in all hot observable add as last operator in pipe:takeUntil(this.destroy$)
. It will unsubscribe when the component is destroyed.