1

I've looked a lot online and haven't been able to find anything that describes my problem.

I'm currently using Angular 5.

Basically, I want to perform a put http request, then once that complete do some stuff, then perform another get http request and do some more stuff.

Here is my code using nested subscriptions (which I know you shouldn't be doing):

this.projectService.updateProject(this.project).subscribe(
  subscribe => {
    doSomethingAfterTheUpdate();
    this.projectService.get(this.id).subscribe(
      subscribe => {
        doSomethingAfterTheGet();
        });
    });

As you can see, I am updating the project, then getting the project. How can I do this properly using RxJS. I've looked into Concat and MergeMap methods, but I want to perform some action after both the update and the get.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • Possible duplicate of [How to chain Http calls in Angular2?](https://stackoverflow.com/questions/34104638/how-to-chain-http-calls-in-angular2) – Jota.Toledo Nov 02 '18 at 17:52
  • @Jota.Toledo I don't think it is a duplicate; the difference is I want to perform some action after executing the first http request AND execute another http request. – ViqMontana Nov 02 '18 at 17:58

2 Answers2

5

You should be able to use operators tap and switchMap to achieve this:

import { switchMap, tap } from 'rxjs/operators';

// ...

this.projectService.updateProject(this.project)
  .pipe(
    tap(() => doSomethingAfterTheUpdate()),
    switchMap(() => this.projectService.get(this.id)),
    tap(() => doSomethingAfterTheGet())
  )
  .subscribe(results => console.log(results));

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
2

You could consider the doSomethingAfterTheUpdate a side-effect, so you could go as:

import { mergeMap, tap } from 'rxjs/operators';

this.projectService.updateProject(this.project).pipe(
   tap(_ => this.doSomethingAfterTheUpdate()),
   mergeMap(_ => this.projectService.get(this.id))
).subscribe(_ => this.doSomethingAfterTheGet());

Note that I use _ on some pipe operations, as you dont really use the scoped values.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
  • Thanks! I actually do need the scoped value from the `this.projectService.get` method. My question is, what if I do another `tap` after the `mergeMap` instead of doing a `subscribe` at the end, what would be the difference, as I have tested this out and it works the same as the subscribe. – ViqMontana Nov 06 '18 at 12:50
  • @Viqas Your original code snippet does not reflect that. Moving the callback from the subscribe into a 2nd `tap` after `mergeMap` would not make a difference. – Jota.Toledo Nov 06 '18 at 13:16