我还在学习 observables,所以如果有一个简单的解决方案,我不会感到惊讶。基本上我现在拥有的是四个嵌套订阅,第二个订阅()中有一个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)
)
),
);