Is it possible to stop the navigation of the router based on any condition

I'm new to angular, I want to stop routing when the user clicks the refresh button or the return button depending on some conditions. I don't know if this is possible if anyone knows help me

constructor(private route: Router) { this.route.events .filter(event => event instanceof NavigationEnd) .pairwise().subscribe((event) => { if (expression === true){ // stop routing } else { // continue routing } }); } 

Is it possible? If so, how can I do this?

+25
angular
source share
2 answers

I came across this question a bit after the fact, but I hope to help someone else come here.

The main candidate for the solution is the route security service.

See here for an explanation: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

The corresponding part (almost literally copied) is the implementation:

 import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { MyComponent} from './my-component/my-component.component'; @Injectable() export class CanDeactivateGuard implements CanDeactivate<MyComponent> { canDeactivate( component: MyComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | boolean { // you can just return true or false synchronously if (expression === true) { return true; } // or, you can also handle the guard asynchronously, eg // asking the user for confirmation. return component.dialogService.confirm('Discard changes?'); } } 

Where MyComponent is your custom component, and CanDeactivateGuard will be registered in your AppModule in the providers section and, more importantly, in your routing configuration in the canDeactivate array canDeactivate :

 { path: 'somePath', component: MyComponent, canDeactivate: [CanDeactivateGuard] }, 
+19
source share

You can use the NavigationStart event, as in the following code snippet.

 this.router.events.subscribe( (event: any) => { if (event instanceOf NavigationStart) { /// Your Logic } }) 
-4
source share

All Articles