我需要创建一个函数来按顺序进行 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 来实现运算符(operator)。此示例使用 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);
});
}
关于Angular - 按顺序进行多个 HTTP 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212448/