【发布时间】:2020-12-09 15:24:08
【问题描述】:
我还在学习 observables,所以如果有一个简单的解决方案,我不会感到惊讶。基本上我现在拥有的是四个嵌套订阅,第二个 subscribe() 中有一个fourEach。我看到了很多使用 switchMap 的答案,但我找不到一个也有一个 for 循环可以迭代的答案。我知道我可能应该使用嵌套订阅,但我不知道如何使用 forEach。
这是嵌套订阅的工作代码:
dialogRef.afterClosed().subscribe(result => {
if(result) {
this.createLikertResponseGroup(result.likertResponseGroup)
.subscribe(likertResponseGroupJSON => {
result.likertResponse.controls.likertResponseFormArray.controls.forEach((element) => {
let characteristic = element.controls.characteristic;
this.newResponseGroupId = likertResponseGroupJSON.LikertResponseGroup.id;
this.createLikertResponse(element, this.newResponseGroupId)
.subscribe(likertResponseJSON => {
if (characteristic) {
let responseId = likertResponseJSON.LikertResponse.id;
this.createCharacteristic(characteristic, this.newResponseGroupId, responseId)
.subscribe(characteristicJSON => {
this.newCharacteristicId = characteristicJSON.Characteristic.id;
});
}
});
});
})
}
});
我现在的作品。所以我的问题是,是否值得改变我这样做的方式?如果是这样,我会怎么做?
我还没有走多远,但我对 switchMap 的尝试看起来像这样:
dialogRef.afterClosed().pipe(
filter(result => result != null),
switchMap(result =>
from(result.likertResponse.controls.likertResponseFormArray.controls).pipe(
// not sure what to do after this (or if I'm even doing it right)
)
),
);
【问题讨论】:
-
使用 switch map 的想法是,第一个“可观察部分”应该返回一个新的 observable,而不是订阅一个新的 observable。
switchMap将在它们之间起到粘合作用,并且基本上将subscribe替换为“完成第一个订阅并切换到另一个”。现在,在您的第一个案例中,您有一个if和两个案例。所以,如果你想使用 switchmap,你必须在这两种情况下都返回一个 observable。什么都不想做的情况下,可以返回Observable.empty。在正常情况下,返回this.createLikertResponseGroup(result.likertResponseGroup) -
作为辅助建议,为了试验可观察对象和学习,您可以使用 StackBlitz。或者只是去
https://rxjs.dev/并打开控制台,rxjs 已加载在那里。只需替换您的实际 API 调用dialogRef.afterClosed()返回一些您硬编码的虚拟 Observable(可能使用一些“setTimeout”来模拟异步性),以及许多console.log以可视化程序的流程。 -
我建议你阅读这篇文章:medium.com/angular-in-depth/…
标签: angular rxjs angular-material angular2-observables