[英]Rxjs prevent subscribe in subscribe
我有一个对象数组。 如果 ids,我需要获取数组,然后调用 2 个 API,然后关闭模态窗口。
我的代码是:
from(this.alerts)
.pipe(map(alert => alert._id))
.subscribe(alertIds => zip(
this.alertApi.someCall1(alertIds, ...),
this.alertApi.someCall2(alertIds, ...),
).subscribe(() => {
this.activeModal.close();
}),
);
你有什么想法阻止subscribe
里面的subscribe
吗?
使用switchMap
rxjs 操作符来避免嵌套订阅。
from(this.alerts)
.pipe(
map(alert => alert._id),
switchMap(alertIds => zip(
this.alertApi.someCall1(alertIds, ...),
this.alertApi.someCall2(alertIds, ...)
))
)
.subscribe(() => {
this.activeModal.close();
);
可以在此处找到有关 switchMap 运算符的更多信息。
您可以使用forkJoin
,这是类似Promise.all
和switchMap
。
from(this.alerts)
.pipe(
switchMap(alert =>
forkJoin(
this.alertApi.someCall1(alert._id),
this.alertApi.someCall2(alert._id)
)
)
)
).subscribe(() => {
this.activeModal.close();
});
请注意,生成的 observable 只有在所有内部 observable 完成时才会发出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.