Search code examples
angularngrx

How do I make sure that I unsubscribed subscribe?


I have a subscription where I get some messages from the store to output toastr.

I unsubscribed by subscribe .unsubscribe().

How can check that I have really unsubscribe?

  subscription!: Subscription;

  ngOnInit(): void { }

  toastrError(): void {
    this.subscription = this.store.select(getMessage).subscribe(m => {
      (m.message && m.title) ? this.toastr.error(m.message, m.title) : null;
    });
  }

  singIn(): void {
    this.toastrError();
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

Solution

  • A component instance has a lifecycle that begins when Angular instantiates the component class and renders the component view (along with its child views). The lifecycle continues with some change detection, as Angular checks to see when data-bound properties change, and in response updates both the view and the component instance when needed. The lifecycle ends when Angular actually destroys the component instance and removes its rendered template from the DOM, so the ngOnDestroy is called immediately before Angular destroys the component (or directive).

    If you want to make sure the unsubscription is actually occurring, you can either add a log at the ngOnDestroy method or debug it in the browser.