Warm tip: This article is reproduced from stackoverflow.com, please click
rxjs

Extract a value from an Observable in RxJs

发布于 2020-03-28 23:13:52

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)?

Questioner
alexander.sivak
Viewed
47
Kamil Augustyniak 2020-01-31 17:43

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;});