Angular - 按顺序进行多个 HTTP 调用 [英] Angular - Make multiple HTTP calls sequentially

查看:39
本文介绍了Angular - 按顺序进行多个 HTTP 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个函数来依次进行 HTTP 调用,以便使用一个调用对另一个调用的响应,例如从第一次调用中获取用户的 IP 地址,并使用该 IP 在第二次调用中注册用户.

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.

演示代码:

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+ 可管道操作符.

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

这篇关于Angular - 按顺序进行多个 HTTP 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆