Search code examples
angularangular-router

Problem when trying to unsubscribe from route subscription


I have a question which is bothering me :)

In service i have:

    const url = this.router.url;
    this.Subscription = router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = url ;
        url  = event.url;
      }
    });
  public unsubscribeNavigation() {
    this.navSubscription.unsubscribe();
  }

  public getLastUrl() {
    return this.previousUrl;
  }

And in component in ngOnInit i am using :

const lastUrl= this.service.getPreviousUrl();
    if (previous.includes('account')) {
      this.onAccountPage = true;
    }

Alongside with:

  public ngOnDestroy(): void {
    this.form.destroy();
    this.service.unsubscribeNavigation();
  }

Code above is working, when i come to component which is inside tab, i am getting last url lets say index. Problem is when i unsubscribe in onDestroy when i leave for another tab. When i came back to this tab my last page is still index because subscription dont exist anymore. How can i overcame that? I want to unsubscribe but again i need that subscription when coming back to tab.


Solution

  • I think the issue that you are having is that the service and the component have different life cycles. If you are using Angular 10 or 11, you can have the service implement OnDestroy and do the unsubscription there.

    class HistoryService implements OnDestroy {
    
    const url = this.router.url;
        this.Subscription = router.events.subscribe((event) => {
          if (event instanceof NavigationEnd) {
            this.previousUrl = url ;
            url  = event.url;
          }
        });
     
        public getLastUrl() {
          return this.previousUrl;
        }
    
        ngOnDestroy() {
         this.navSubscription.unsubscribe();
        }
         
    }

    I removed the call to this.service.unsubscribeNavigation() when the component is destroyed.