Stephen McGowan
Stephen McGowan

Reputation: 69

How to chain API calls in rxJs subscribe and map with Angular?

I'm performing multiple API calls. One creates a User and the second Creates a Team.

User creation returns a UserId, which is then used as part of the Team creation.

I'm using rxjs library with Angular, using the .map and .subscribe methods to wait until the first call is resolved, then pass the UserId to the second api call.

The first call is resolving and returning the UserId I need, but the second isn't even sending.

    this.http.post<number>(this.baseUrl + 'api/register/', UserTeam, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    })
      .map(response => response)
      .subscribe(result =>
      //result = the new user id from registering new user
      {
        var newTeam = JSON.parse(UserTeam);
        newTeam.userId = result;
        newTeam = JSON.stringify(newTeam);
        this.http.post(this.baseUrl + 'api/team/', newTeam, {
          headers: new HttpHeaders({
            "Content-Type": "application/json"
          })
        }).map(result => result)
      })

I've debugged and when the URL is built, it should be hitting my endpoint, and the body I'm sending with it is successful on the URL when tested on postman, I'm not sure why the call isn't sending.

It seems to me that it should make the second API call.

I've tried using .pipe and then .map, but this doesn't work either.

When debugging the code it navigates through both calls, and the second .map(result => result) contains the same id returned from the response => response.

This makes me think I can only make one API call before unsubscribing, can anyone provide any clarity on this.

Upvotes: 0

Views: 3370

Answers (1)

mbojko
mbojko

Reputation: 14669

The second stream doesn't get subscribed.

With current RxJS syntax, it should look more or less like this

this.http.post(/* args here */)
  .pipe(
    switchMap(result => {
      /* do something with result */
      return this.http.post(/* args here */)
    })
  ).subscribe( /* subscriber here */)

Upvotes: 1

Related Questions