0

In one of my components I have a function that updates a local observable (album$) which is then used in my html to display the data (*ngIf="album$ | async as album"). This works perfectly fine.

  getData() {
    this.album$ = this._activatedRoute.params.pipe(
      tap(params => {
        // Update variables
      }),
      switchMap(params => {
        return this.service.getData(params.id, params.id2);
      })
    )
  }

However, a new requirement means that I need to update a BehaviorSubject I have in one of my services. The function above seemed like a great place to kill two birds with one stone.

I would like to perform a patchValue and this.service.obs$.next once the function above returns it's data.

I do achieve this functionality in a separate component I have, but as I'm not using a subscription in the one above, how would i go above adding this.service.album$.next(data); to my above function?

// Example of another function that has the functionality i'm pretty much after, but is subscription based.

  getData(){
    this._subscription = this._activatedRoute.params.pipe(
      tap(params => {
        // update variables
      }),
      switchMap(params => {
        return this.service.getData(params.id1, params.id2);
      })
    ).subscribe(data => {
      if (data) { 
        this.service.obs$.next(data);
      } 
    });
  }
Haven
  • 87
  • 1
  • 9

1 Answers1

2

You could pipe in tap or map to the inner observable. Try the following

getData() {
  this.album$ = this._activatedRoute.params.pipe(
    tap(params => {
      // update variables
    }),
    switchMap(params => {
      return this.service.getData(params.id, params.id2).pipe(
        tap(data => {
          this.service.obs$.next(data);
          // patch value
          // do something else
        })
      );
    })
  );
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • how is switching from `tap` to `map` not depending on side effects? ;) – ggradnig Jul 21 '20 at 09:31
  • 1
    I just about to accept the above answer, but now i'm curious about the above question :) – Haven Jul 21 '20 at 09:32
  • @Haven: That's a valid point. There's essentially no use in using `map` if the value isn't modified. I've adjusted the answer to use `tap`. – ruth Jul 21 '20 at 10:42
  • When you say the value isn't modified, do you mean once it's obtained or if it changes from the source? Wondering if i'm understanding that properly – Haven Jul 21 '20 at 11:23
  • I meant, `map` is useful if the data from the observable is modified in anyway and the modified value is returned. But we aren't modifying the data from the inner observable in any way, there is no difference between `tap` and `map` here. – ruth Jul 21 '20 at 11:25
  • Gotcha! - Thanks for your time! – Haven Jul 21 '20 at 11:32
  • Also, you don't need to have the pipe on the 2nd observable. You can simply add that same tap after switchMap to avoid nesting. – cjd82187 Jul 21 '20 at 12:38