Reputation: 9457
Using Angular I am new to RXJS observables and trying to get my head around this error. I have the following basic code:
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();
}
}
In summary I have an event service with a rxjs subject called test$. In my component I have three functions watch, test, unsubscribe. All of which are connected to buttons in the html template.
I run in the component, 'watch()' which subscribes to the subject. I then run 'test()', which print's 'Hello World' in the console. I then run unsubscribe() which I assume unsubscribes to test$.
The issue is when I run test() again I get an error 'ObjectUnsubscribedError'. What is the reason for this and solution? I assume it is do with how I am unsubscribing to the test$?
Many thanks advance.
Upvotes: 1
Views: 360
Reputation: 692161
That's not how you unsubscribe. You unsubscribe by calling unsubscribe()
on the Subscription returned by 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();
}
}
}
Here's your demo.
The method Subject.unsubscribe()
has no documentation, so it's hard to explain what it does and why it exists, unfortunately.
Upvotes: 1