代码之家  ›  专栏  ›  技术社区  ›  Abdul Rafay

角度-按顺序进行多个http调用

  •  10
  • Abdul Rafay  · 技术社区  · 7 年前

    我需要做一个函数来按顺序进行http调用,以便使用一个调用到另一个调用的响应,比如从第一个调用获取用户的ip地址,并使用该ip在第二个调用中注册用户。

    演示代码:

    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);
    }
    
    1 回复  |  直到 7 年前
        1
  •  14
  •   Alexander Staroselsky    7 年前

    这可以通过使用 switchMap 接线员。本例使用rxjs 5.5+可管道运算符。

    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);
        });
    }
    

    希望能帮上忙!