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)
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
15710 次 |
| 最近记录: |