Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

typescript - Angular - Make multiple HTTP calls sequentially

I need to make a function to make HTTP calls sequentially inorder to use response of one call into other one like getting IP address of user from first call and use that IP to register user in second call.

Demo code:

registerUser(user: User) {
    this.utility.getIpAddress()
    .subscribe(data => {
        this.ipAddress = data.ip;
    });
    const body = {
        UserName: user.UserName,
        Email: user.Email,
        //...
        UserIP: this.ipAddress,
    }
    return this.http.post(this.registerAPI, body);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This can be achieved using the switchMap operator. This example uses RxJS 5.5+ pipeable operators.

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress().pipe(
    switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    })
  )
}

RxJS < 5.5:

import { switchMap } from 'rxjs/operators';

registerUser(user: User) {
  return this.utility.getIpAddress()
    .switchMap(data => {
      this.ipAddress = data.ip;

      const body = {
        UserName: user.UserName,
        Email: user.Email,
        UserIP: this.ipAddress,
      };

      return this.http.post(this.registerAPI, body);
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...