Angular Guard to allow only previously visited routes

Viewed 77

I'm working on making a steps wizard, and trying to prevent the user from navigating to the upcoming pages routes unless they navigate through the steps, but allow them to navigate to the previous pages/steps.

My current solution is to specify a step number for each page/step, but it doesn't allow navigating to previous steps:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> | boolean {
  this.insuranceStepService.getCurrentStepNum().pipe(delay(100)).subscribe(stepNum => {
     switch(stepNum) {
        case 1:
           this.router.navigate([AppRoutes.StepA]);
           return true;
        break;
        case 2:
           this.router.navigate([AppRoutes.StepB]);
           return true;
        break;
        default:
           this.router.navigate([""]);
           return false;
        break;
     }
  });

  return true;
}
1 Answers

Could you just keep the state in an object. When visited / allowed to visit mark that step by adding the key to the state.

Setup:

const stepState = {};

On navigate to new step (or when step validates)

stepState.nextStep = true;

In navigation handler:

if(stepState[requestedStep]) {
    this.router.navigate([requestedStep]);
}
Related