angular - 在一个角度函数中分别调用两个订阅而不混合它们
问题描述
我试图在一个角度函数中调用 2 个订阅请求,不幸的是只完成了第一个请求
debugger;
this.tableService.UpdateTableStatus(tableCode).subscribe(result => {
this.statusUpdatedSuccessfully = result;
if (this.statusUpdatedSuccessfully === true) {
this.flag = true;
alert('statusUpdatedSuccessfully');
}
});
this.newOrder.employeeCode = this.employee.globalPassword;
this.newOrder.orderTime = new Date();
this.newOrder.restaurantTableCode = tableCode;
this.newOrder.totalpayment = 0;
this.orderService.addNewOrder(this.newOrder).subscribe(result => {
// tslint:disable-next-line: no-debugger
debugger;
this.orderCode = result;
this.tableToAdd.orderCode = this.orderCode;
this.tableToAdd.tableCode = tableCode;
this.orderService.listBusyTable.push(this.tableToAdd);
});
this.router.navigate(['/orders-in-process', tableCode]);
}
解决方案
我敢打赌这是因为你在它有机会进入第二个之前就已经离开了subscribe
。
asubscribe
中的Asubscribe
是反模式,因此使用 aswitchMap
切换到新的 observable。
import { switchMap } from 'rxjs/operators';
....
debugger;
this.tableService.UpdateTableStatus(tableCode).pipe(
switchMap(result => {
this.statusUpdatedSuccessfully = result;
if (this.statusUpdatedSuccessfully === true) {
this.flag = true;
alert('statusUpdatedSuccessfully');
}
});
this.newOrder.employeeCode = this.employee.globalPassword;
this.newOrder.orderTime = new Date();
this.newOrder.restaurantTableCode = tableCode;
this.newOrder.totalpayment = 0;
return this.orderService.addNewOrder(this.newOrder);
})
).subscribe(result => {
this.orderCode = result;
this.tableToAdd.orderCode = this.orderCode;
this.tableToAdd.tableCode = tableCode;
this.orderService.listBusyTable.push(this.tableToAdd);
// once the API call of addNewOrder is done and subsribed to here,
// navigate away
this.router.navigate(['/orders-in-process', tableCode]);
});
}
如果要保留inside ,则必须将行移到第二个订阅回调的subscribe
内部。subscribe
router.navigate
推荐阅读
- javascript - 将图像拖放到 div 上
- ios - 按下 UIAlertViewController 行时更改背景颜色
- python - 为什么我的装饰器按这个顺序执行代码?
- c# - 如何从 c# windows 应用程序向 PHP 服务器发送包含对象数组的 POST 请求?
- c# - POST 带有 URL 参数但正文为空时如何使用 ServiceStack 的 ProxyFeature?
- c# - Visual Studio 2019 中的 Visual Inheritance 似乎有问题
- java - 无法从 REST API 获取 JSON 作为字符串
- c# - ASP.NET CORE 2.0 项目中的 LinkedIn 登录集成
- python-3.x - ModuleNotFoundError:没有名为“py4j”的模块
- python-3.x - 河内塔最多允许 100 个