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

Abd*_*fay 15 observable typescript angular

我需要创建一个函数来顺序进行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);
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*sky 15

这可以使用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);
    })
  )
}
Run Code Online (Sandbox Code Playgroud)

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!

  • @AlexanderStaroselsky:原谅我的天真,但是用this.utility.getIpAddress()返回的return不会解决这个问题吗? (2认同)