订阅我的Observable时遇到了一些问题
我有一个组合Observable:
private selectedEntryId$ = new Subject<number>();
private entries$ = new Subject<MappingEntry[]>();
private selectedEntry$ = Observable.combineLatest(
this.entries$,
this.selectedEntryId$,
(entries: MappingEntry[], id: number) => {
return entries.find((entry: MappingEntry) => {
return entry.id === id;
});
});
我每次都尝试做API调用,当我的 selectedEntry$
有下一个值并以这种方式订阅结果时:
constructor(private checkService: CheckService) {
this.subscribeLengthCalculator();
}
subscribeLengthCalculator() {
this.subscriptions.add(
this.selectedEntry$
.switchMap((entry) => {
return entry ? this.checkService.calculateLinesLength([entry.value]) : Observable.empty();
}).subscribe(([calculation: CalculationObject]) => {
console.log(calculation);
this.calculation = calculation;
})
);
}
第一次当 selectedEntry$
有下一个值时, console.log
向控制台抛出正确的API结果,但在我的html calculation
中有空值 . 当 selectedEntry$
具有第二个下一个值时, console.log
也会向控制台发出正确的API结果,但在html中显示mi之前的值 . 任何人都可以解释我这种行为并告诉我应该怎样做才能在html中显示当前数据?这是非常奇怪的行为 .
1 回答
引用learnrxjs“但要小心,你可能想避免在需要完成每个请求的场景中使用
switchMap
” .“
switchMap
与其他展平运算符之间的主要区别在于取消效果”,这就是当selectedEntry$
具有第二个下一个值时,它会显示您之前的值 . 源可观察(this.selectedEntry$
)a;准备完成,订阅仅对来自此行的Observable
有效:所以,说到这一点,我建议你尝试
concatMap
而不是switchMap
:但事实上,我喜欢管道运营商,所以答案是: