Search code examples
angular

Ignore can-activate guard by passing parameter in router.navigate


I am looking for a solution to ignore one-time guard by passing parameter/flag/etc. in router navigate.

Current configuration:

  • standard routing with auth canActivate: [CanActivateGuard]
  • resolver - checking the subpath application - for loading snapshot, when the user got URL with some path, can load application,

Problem:

  • above mechanism working great (snapshot, generate lost ngrx store data etc.)
  • but in guard I am checking if some value exists in store:
  canActivate(): boolean {
    let canActivate = false;
    this.store$.pipe(select(selectSth), take(1)).subscribe(item => {
      if (!!item) {
        return canActivate = true;
      }
      this.router.navigate(['/main']);
      return canActivate = false;
    });
    return canActivate;
  }
}
  • canActivate was checked before resolver - so I can't navigate to /main path even the parameter exists in store

Question:

There is any solution to add parameter to this.router.navigate and one time avoid guard?


Solution

  • The thing is that, in Angular, all guards should be executed before any resolver, so if you have child routes with guards, they'll block parent resolvers unless all of the guards succeed.

    This logic means that the data for a guard should exist already (App Init) or be loaded by the guard.

    A possible solution is to move data loading logic to the guard, and if the guard succeeds, then the corresponding resolver would simply select the data from the store.

    If you don't plan to use guards and resolvers together all the time, you might introduce a service which loads data if it is needed and to rely on the service in both classes: the guard and the resolver.