0

I'd like to execute one http get request after another has completed. The endpoint URL for the second request will need to depend on the first request.

I've tried nesting the requests with something like this in Angular:

this.http.get(endpoint1).subscribe(
   success => {
      this.http.get(endpoint2 + success).subscribe(
         anotherSuccess => console.log('hello stackoverflow!')
      );
   }
);

First question here on stackoverflow, please let me know if I should provide more detail.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
edric-m
  • 3
  • 3

2 Answers2

0

here you can find how to do that, you have various options:

with subscribe:

this.http.get('/api/people/1').subscribe(character => {
  this.http.get(character.homeworld).subscribe(homeworld => {
    character.homeworld = homeworld;
    this.loadedCharacter = character;
  });
});

with mergeMap

this.homeworld = this.http
  .get('/api/people/1')
  .pipe(mergeMap(character => this.http.get(character.homeworld)));

There is a version with forkJoin but isn't explicit compared with subscribe and mergeMap.

Oscar Velandia
  • 1,157
  • 1
  • 7
  • 9
0

You should probably try using ngrx (redux) triggering the second request depending on a success action.

The flow should be something like this: dispatch an action from a component -> call the first request -> the request triggers a success action -> success effect triggers the second request with a payload from the previous request.

enter image description here

Read the docs here