Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 check next route OnDestroy

I am trying to trigger action on any NavigationEnd router event, except when navigating between a) child routes; b) on one another specific route.

Here is a piece of my app.routing.ts:

// some other routes setup...

{ path: 'scrapers/:version', component: SingleScraperComponent, children: [
    { path: '', redirectTo: 'statistics', pathMatch: 'full' },
    { path: 'statistics', component: ScraperStatisticComponent },
    { path: 'targets', component: ScraperTargetsComponent },
]},

// some other routes setup...

Here is my Router events subscription in SingleScraperComponent:

// some component code

ngOnInit(): void {
    this._router.events.filter(event => event instanceof NavigationEnd).takeWhile(() => this.isAlive).subscribe(
        (event: NavigationEnd) => {
            console.log(event);
            if (event.url.indexOf('site-preview') === -1) {
               this._site.resetQuery();
            }
        }
    );
}

// some component code

I could also use OnDestroy, but I need to know next route after SingleScraperComponent destruction.

like image 406
markoffden Avatar asked Nov 27 '17 12:11

markoffden


People also ask

How do I check Angular routes?

Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What is Ondestroy in Angular?

OnDestroylinkA lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.

What is NavigationEnd?

NavigationEndlinkAn event triggered when a navigation ends successfully.


1 Answers

Ok, I have used routerState snapshot to verify next route:

ngOnDestroy(): void {
    if (this._router.routerState.snapshot.url.indexOf('site-preview') > -1) {
        console.log('Hello, from needed route!');
    }
}

But if there is a more clear way I would appreciate to know.

like image 184
markoffden Avatar answered Nov 10 '22 01:11

markoffden