简体   繁体   中英

Angular RXJS Observables - ObjectUnsubscribedError

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM