繁体   English   中英

Angular - 按顺序进行多个 HTTP 调用

[英]Angular - Make multiple HTTP calls sequentially

我需要创建一个函数来按顺序进行 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);
}

这可以使用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);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM