我在组件基类中有以下代码:
//@Directive()
//export abstract class BaseComponent {
unsubscriber$ = new ReplaySubject(1);
ngOnInit(): void {
this.oAuthService.events
.pipe
(
filter(event => event?.type === 'logout'),
takeUntil(this.unsubscriber$),
tap(() => {
this.unsubscriber$.next(null);
this.unsubscriber$.complete();
})
)
.subscribe();
}
//}
这个想法 - 取消订阅当我按下“注销”按钮时正在加载的任何 API 服务调用:
//export class SomeComponent extends BaseComponent {
this.someService
.someApiMethod()
.pipe(takeUntil(this.unsubscriber$))
.subscribe(() => {
...
});
//}
但是,这样的取消订阅似乎不起作用 - 在调用“tap”内的代码之后 -
someApiMethod
仍然被调用(当然会产生错误 401)。我是不是错过了什么?
仅供参考。我以与
this.unsubscriber$
相同的方式使用 ngOnDestroy
,并且它按预期工作。
尝试将订阅移至构建时间,以确保它是第一个被处理的订阅。也可以稍微重构一下
//@Directive()
//export abstract class BaseComponent {
unsubscriber$ = new ReplaySubject(1);
constructor(oAuthService:OAuthService) {
oAuthService.events
.pipe
(
filter(event => event?.type === 'logout'),
take(1)
)
.subscribe(()=>{
this.unsubscriber$.next(null);
this.unsubscriber$.complete();});
}
//}
还要确保某些异步调度程序上的
oAuthService.events
不是 observedOn
也不是 subscribeOn