Angular 10 - canActivate Guard Prevents Navigation to Correct URL When Entered Manually

856 Views Asked by At

In my Angular 10 application, I have a route with several child routes, that has a canActivate guard on it.

{
    path: 'settings', component: SettingsComponent,
    children: [
      { path: '', redirectTo: 'index-types', pathMatch: 'full' },
      {
        path: 'index-types', component: IndexTypesComponent,
        resolve: [IndexTypeResolverService],
        canActivateChild: [ErrorPageGuard],
        children: [
          { path: '', component: IndexTypeStartComponent },
          { path: 'new', component: IndexTypeEditComponent },
          {
            path: ':id',
            component: IndexTypeDetailComponent,
            resolve: [IndexTypeResolverService]
          },
          {
            path: ':id/edit',
            component: IndexTypeEditComponent,
            resolve: [IndexTypeResolverService]
          }
        ]
      },
      { path: 'users', component: UsersComponent }
    ]
  }

I'm trying to get the canActivtate guard to prevent the user from entering a URL with an Id that doesn't exist in the :id and the :id/edit routes. The canActivate seems to do a good job in preventing the user from entering a non existent id in the URL, but the problem is that when the user enters the URL manually a correct id, it behaves the same as if it were incorrect - but when clicking a routerLink with the same correct id it works.

I tried to debug it, and have reached the conclusion that, in the following code, the this.indexTypeService that's supposed to have a list of my indexTypes doesn't actually have anything in that list, only in the case when the user enters anything manually in the address bar:

export class ErrorPageGuard implements CanActivate, CanActivateChild {

  constructor(private indexTypeService: IndexTypeService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    //TODO: works when navigating programmatically, but not when navigating manually

    let state_id = state.url.split('/')[state.url.split('/').length - 1];
    let route_id = +route.params.id;
    let id = Object.keys(route.params).length > 0 ? route_id : (!isNaN(+state_id) ? +state_id : -1);


    if ((Object.keys(route.params).length === 0)
      || (this.indexTypeService.getIndexType(id) !== undefined)) {
      return true;
    }
    else {
      this.router.navigate(['/']);
      return false;
    }
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(route, state);
  }
}

What am I doing wrong?

0

There are 0 best solutions below