Angular - Make multiple HTTP calls sequentially

前端 未结 1 1879
一生所求
一生所求 2020-11-30 10:05

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

相关标签:
1条回答
  • 2020-11-30 10:23

    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);
        });
    }
    
    0 讨论(0)
提交回复
热议问题