Angular-依次进行多个HTTP调用

问题描述 投票:16回答:1

我需要创建一个函数来依次进行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);
}
angular typescript observable
1个回答
16
投票
这可以使用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); }); }

© www.soinside.com 2019 - 2024. All rights reserved.