[使用Angular,我是RXJS可观察对象的新手,并试图解决这个错误。我有以下基本代码:
export class EventService {
test$ = new Subject();
watch() {
return this.test$;
}
push() {
this.test$.next('Hello World');
}
}
export class Component {
watch() {
this.eventService.watch().subscribe((obj)=>{ console.log('Helo', obj)});
}
test() {
this.eventService.push();
}
unsubscribe(){
this.eventService.watch().unsubscribe();
}
}
总之,我有一个事件服务,带有一个名为test $的rxjs主题。在我的组件中,我具有监视,测试和退订三个功能。所有这些都连接到html模板中的按钮。
我在订阅主题的'watch()'组件中运行。然后,我运行“ test()”,在控制台中打印“ Hello World”。然后,我运行unsubscribe(),假设我取消订阅了test $。
问题是,当我再次运行test()时,出现错误'ObjectUnsubscribedError'。这是什么原因和解决方案?我认为这与我退订test $的方式有关?
非常感谢。
这不是您退订的方式。您可以通过在unsubscribe()
返回的订阅上调用subscribe()
来取消订阅:
export class Component {
private subscription: Subscription;
watch() {
this.subscription = this.eventService.watch().subscribe((obj)=>{ console.log('Helo', obj)});
}
test() {
this.eventService.push();
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
不幸的是,Subject.unsubscribe()
方法没有任何文档,因此很难解释它的作用及其存在的原因。