angular - 在 ngOnInit() 中等待第一次调用(订阅)
问题描述
我需要等待第一个电话,然后再开始第二个请求。我是 js 新手,所以我认为它可能很简单。我读过关于 async/await 的消息,但我不知道如何在这个例子中实现它
ngOnInit() {
this.firstService.get$(this.orderNumber).subscribe(
first => this.firstModel = first,
e => {
for (const error of e.errors) {
this.messages.push({
_type: MessageType.ERROR,
code: error.messageCode
});
}
}
);
this.secondService.getReasons$(this.firstModel).subscribe(
second => this.secondModel = second,
e => {
for (const error of e.errors) {
this.messages.push({
_type: MessageType.ERROR,
code: error.messageCode
});
}
}
);
}
this.firstModel
在第二步中未定义。
解决方案
您必须使用switchMap()
rxjs 运算符来帮助您获得第一个响应,然后定位第二个请求。如果不需要,您可以取消请求。
以下代码分为许多部分,以便于理解。如果你喜欢,你可以结合所有。
// Define both requests
const firstReq = this.firstService.get$(this.orderNumber)
const secondReq = this.secondService.getReasons$(this.firstModel);
// combined has both response
const combined= firstReq.pipe(switchMap(firstData =>{
return secondReq ;
}))
combined.subscribe()
为方便起见,您可以使用tap
运算符来检查两个响应
const combined= firstReq.pipe(switchMap(firstData =>{
return secondReq.pipe(tap(secondData =>{
console.log('First request data',firstData);
console.log('Second request data',secondData);
}))
}))
combined.subscribe()
推荐阅读
- javascript - 了解屏幕外画布以提高性能
- html - 为什么 z-index 不适用于绝对位置的元素?
- python - 我无法让组列表通过它迭代我的方法(pygame.sprite)
- assembly - 两个逻辑运算之间的异或运算
- python-3.x - 如何为空的numpy数组赋值
- reactjs - 浏览器返回在 reactjs 应用程序中不起作用
- gnuplot - 错误:“需要完整使用 x 时间数据的规范”
- c# - C#远程服务器返回错误:(401) Unauthorized
- java - 为什么我没有从这个 java 程序中得到任何输出?
- java - 如何查找 spring 数据存储库子类型的 save(...) 方法的引用