我在订阅我的可观察量时遇到了一点问题
我有一个组合可观察的:
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中显示当前数据?这是非常奇怪的行为。
引用 learnrxjs "不过要小心,你可能希望避免在每个请求都需要完成的情况下switchMap
"。
"switchMap
和其他平展运算符之间的主要区别在于取消效果",这就是为什么当selectedEntry$
有第二个下一个值时,它会显示您之前的值。源可观测 (this.selectedEntry$
( a;就绪完成,订阅仅对来自此行的Observable
处于活动状态:
return entry ? this.checkService.calculateLinesLength([entry.value]) : Observable.empty()
因此,话虽如此,我建议您尝试concatMap
而不是switchMap
:
subscribeLengthCalculator() {
this.subscriptions.add(
this.selectedEntry$
.concatMap((entry) => {
return entry ? this.checkService.calculateLinesLength([entry.value]) : Observable.empty();
}).subscribe(([calculation: CalculationObject]) => {
console.log(calculation);
this.calculation = calculation;
})
);
}
但事实上,我喜欢管道运营商,所以答案将是:
import { concatMap } from 'rxjs/observable/concatMap';
subscribeLengthCalculator() {
this.subscriptions.add(
this.selectedEntry$
.pipe(
concatMap((entry) => {
return entry ? this.checkService.calculateLinesLength([entry.value]) : Observable.empty();
})
).subscribe(([calculation: CalculationObject]) => {
console.log(calculation);
this.calculation = calculation;
})
);
}