Angular 角度RXJS观测值-对象取消订阅错误
使用角度,我对RXJS的可观测性还不熟悉,并试图了解这个错误。我有以下基本代码:Angular 角度RXJS观测值-对象取消订阅错误,angular,rxjs,Angular,Rxjs,使用角度,我对RXJS的可观测性还不熟悉,并试图了解这个错误。我有以下基本代码: export class EventService { test$ = new Subject(); watch() { return this.test$; } push() { this.test$.next('Hello World'); } } export class Component { watch() { this.eventService.watch
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()时,会出现错误“ObjectUnsubscribedError”。原因和解决方案是什么?我想这与我如何取消订阅考试有关$
非常感谢 你不是这样取消订阅的。通过对
subscribe()
返回的订阅调用unsubscribe()
取消订阅:
给你
方法Subject.unsubscribe()
没有文档,因此很难解释它的作用以及它存在的原因
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();
}
}
}