Routing Guard does not have correct route specified in RouterStateSnapshot

191 views Asked by At

I have a Guard on my routes to prevent unauthorised access. The guard checks the session and calls logon service if not valid. I have routes configured as follows...

const routes: Routes = [
    { path: 'logon', loadChildren: './logon/logon.module#LogonModule' },
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', loadChildren: './home/home.module#HomeModule', canActivate: [HomeGuard] },
    { path: 'forms', loadChildren: './forms/forms.module#FormsModule', canActivate: [FormsGuard] },
    { path: 'processes', component: ProcessesComponent, canActivate: [ProcessGuard] },
    { path: '**', redirectTo: 'home' }
];

Code snippet from the Guard...

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      // This always reports home !
      alert('Logon Guard - State = ' + state.url);

      if (this.logonService.IsLoggedOn()) {
        return true;
      } 
      else {
        // Tell the clientApp what url was in use when calling the canActivate.
        this.logonService.RedirectUrl = state.url;

        this.router.navigate(['logon']);
        return false;
      }
  }

I wanted to re-route to the originally requested route after logon, and tried to use the RouterStateSnapshot url to get the requested route. Howevever it ALWAYS holds the route specified in the default..

{ path: '', redirectTo: 'home', pathMatch: 'full' },

So if I browse to the 'process' route, i.e. 'http://localhost:4200/process' the canActivate in the guard will always hold the 'home' route in the RouterStateSnapshot url property.

I have seen the following similar request... Angular 2 RouterStateSnapshot not returning correct url

I've tried the suggestion of specifying a different guard per route (out of desperation) but this does not work. This is surely not the answer anyway? I should be able to share an authentication Guard among routes?

I'm using Angular 4.

0

There are 0 answers