【发布时间】:2018-03-30 00:54:55
【问题描述】:
我目前正在调查RxJS's .merge,但我也会在这里问这个问题,因为我有时会发现这里的解释很精彩。
好的,我有一个表单,它根据用户输入打开一个模态窗口,我订阅模态关闭事件并传回一些数据,这些数据在我调用/订阅服务方法以检索一些数据后将使用,然后当这种情况发生时,我再次执行相同的操作并调用/订阅另一个服务方法来更新某个日期,然后当这完成后我运行一个本地方法。所以我这里有3个嵌套的.subscribes
const dialogRef = this.matDialog.open(ModalWindowComponent, {});
let userId = 4; // this is the real world is selected by the user
let userData = {}; // this is actually form data created by the user
// dialog is closed
dialogRef.afterClosed().subscribe((result) => {
if (typeof result === 'string') {
// subscribe to a service to get some data
this.userService.getUser(userId).subscribe((user: any) => {
// do something with the data
let mergedObj = Object.assign({}, user, {newProperty: result});
// subscribe to another service to update the data
this.scbasService.updateUser(userId, mergedObj).subscribe(() => {
this.doSomethingElse(userData);
});
});
}
});
我这里有一个“厄运金字塔”。我记得在使用 AngularJS 并使用 promises 时,我可以返回下一个服务并链接.then()s。我真的很想扁平化我的代码,有什么想法吗?
我怎样才能在这里做同样的事情,这样我的代码就不会不断缩进?
如果我没有很好地提问或解释自己,请说出来,我会改写我的问题。
【问题讨论】:
标签: angular typescript rxjs observable