Search code examples
angularangular-ui-routerangular2-routing

Prevent routing in Angular when user manually changes url in browser tab


I am stuck in a issue that happens when user manually changes the route in browser tab and presses enter. This forces my ui-router/angular2-router to navigate to the state entered by user. I want to prevent this and allow routing only through the flow I have implemented by button clicks in my website.


Solution

  • Its 2018! Angular 5 is here and so is the solution to this issue. BAMM its CanActivate Interface that a class can implement to be a guard deciding if a route can be activated.

    We can add this functionality and prevent the access to some of our routes based on the conditions we define. A service for eg AuthGuard that implements the CanActivate interface and defines the canActivate method can be added to route configuration.

    class Permissions {
      canGoToRoute(user: UserToken, id: string): boolean {
        return true;
      }
    }
    
    @Injectable()
    class AuthGuard implements CanActivate {
      constructor(private permissions: Permissions, private currentUser: UserToken) {}
    
      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean>|Promise<boolean>|boolean {
        return this.permissions.canGoToRoute(this.currentUser, route.params.id);
      }
    }
    

    If we have a route that we want to protect access to against some condition, we add the guard as follows:

    const appRoutes: Routes = [
      { path: 'crisis-center', component: CrisisListComponent },
      {
        path: 'heroes',
        canActivate: [AuthGuard],
        component: HeroListComponent,
        data: { title: 'Heroes List' }
      },
      { path: '',
        redirectTo: '/heroes',
        pathMatch: 'full'
      },
      { path: '**', component: PageNotFoundComponent }
    ];
    

    Here the route heroes and all its children have a layer of guard over it. Hence based on the boolean value returned by the AuthGuard service the user will be allowed or denied access to this route.