Typescript rxjs在两个单独的步骤中(针对一个主题)进行管道和订阅,但未按预期工作
这让我头疼。。。以下代码按预期工作:Typescript rxjs在两个单独的步骤中(针对一个主题)进行管道和订阅,但未按预期工作,typescript,rxjs,rxjs6,Typescript,Rxjs,Rxjs6,这让我头疼。。。以下代码按预期工作: const s$ = new Subject<any>(); s$.pipe( switchMap( x => { debugger; return myService.getSth(); } ) ).subscribe(x => { debugger; }); s$.next(); 我错过了什么?对可观察对象
const s$ = new Subject<any>();
s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
).subscribe(x => {
debugger;
});
s$.next();
我错过了什么?对可观察对象(包括主体)调用
.pipe
不会修改该可观察对象的功能,而是会生成一个新的可观察对象。在您的第一个示例中,您对新的可观察对象调用subscribe。在第二个示例中,您对新的可观察对象不做任何操作,然后订阅原始的未映射主题。如果没有任何东西引用新的可观察对象,它就丢失了
将.pipe
的结果保存到变量中,然后订阅该变量:
const mapped$ = s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
);
mapped$.subscribe(x => {
debugger;
});
s$.next();
尴尬。。。当时没有完全了解管道的内部工作,谢谢。默认情况下,RxJS可观察对象是冷的,这正是您99%的时间都不想要的。
const mapped$ = s$.pipe(
switchMap(
x => {
debugger;
return myService.getSth();
}
)
);
mapped$.subscribe(x => {
debugger;
});
s$.next();