Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a method when a user navigates away from a page/route: Angular2

Tags:

angular

I'm trying to run a function whenever current route is changed. For example, if we are currently on "..../user/user-details", where user-details is a separate component. I want to execute a method whenever the route is changed (shouldn't matter if route changes from the UI or directly from the URL). I did something in the user-details component:

constructor(private router: Router) {
  router.events.subscribe(() => {
    console.log('Route changed');
 });
}

But the issue with this approach is, it runs on every route change (whether or not we are navigating to or from user-details page). So this is subscribing to app wide routes. I just want it to run whenever we are navigating away from user-details component. Is their a way to do that?

like image 770
Aiguo Avatar asked Jul 05 '17 13:07

Aiguo


People also ask

What is angular routing and navigation?

This page will walk through Angular routing and navigation example. Using Angular router we can navigate from one view to next while performing our task. Every component can be mapped with a URL and when that URL is accessed by browser or by a link on the page then the corresponding component is displayed.

How to navigate from one view to next using angular router?

Using Angular router we can navigate from one view to next while performing our task. Every component can be mapped with a URL and when that URL is accessed by browser or by a link on the page then the corresponding component is displayed. We can pass optional parameter with the URL that will be fetched in component to filter data to display.

How to implement same route refresh event in angular router?

The first approach is to tell the Angular router to emit the route events on refresh and then handle them accordingly in our routed component. In early Angular versions, there was no option to tell the router to emit events on same route refresh. Angular 5.1 introduced the onSameUrlNavigation property on the routers ExtraOptions.

Is it possible to listen to navigation events in angular?

In that case you you can listen to Angular's navigation events like below: Sorry, something went wrong. @abhayastudios - in the code you posted here, you are unsubscribing in ngOnDestroy. NgOnDestroy won't necessarily fire when you navigate away from the angular component, since NativeScript caches the component.


1 Answers

If you want to just run code when leaving the user-details component then you need to create a CanDeactivate Guard on the route.

Setup the guard so that the UserDetailsComponent implments a interface with a method to call before the route gets deactivated. Then register the CanDeactivate Guard on the route and inside the guard call the method on the route.

interface BeforeUnload {
    beforeunload(): Observable<boolean>|Promise<boolean>|boolean;
}

@Component({ /* ... */})
class UserDetailsComponent implements BeforeUnload {
    beforeUnload() {
        /* ... custom code ... */
        return true;
    }
}

@Injectable()
class CanDeactivateComponent implements CanDeactivate<T extends BeforeUnload> {
  constructor() {}

  canDeactivate(
    component: T,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return component.beforeUnload();
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'user/user-details',
        component: UserDetailsComponent,
        canDeactivate: [CanDeactivateComponent]
      }
    ])
  ],
  providers: [CanDeactivateComponent]
})
class AppModule {}

In this example I set it up so that the route won't leave until the method on the component returns a response but you could immediately return true depending on if beforeUnload is synchronous or not.

like image 83
Teddy Sterne Avatar answered Nov 15 '22 06:11

Teddy Sterne