【发布时间】:2020-02-10 02:24:49
【问题描述】:
使用 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();
}
}
总之,我有一个带有 rxjs 主题的事件服务,名为 test$。在我的组件中,我有三个功能手表、测试、取消订阅。所有这些都连接到 html 模板中的按钮。
我在订阅主题的组件“watch()”中运行。然后我运行'test()',它在控制台中打印'Hello World'。然后我运行 unsubscribe() 我假设取消订阅 test$。
问题是当我再次运行 test() 时出现错误“ObjectUnsubscribedError”。这是什么原因以及解决方法?我认为这与我退订 test$ 的方式有关?
非常感谢提前。
【问题讨论】: