Configure Angular router guard

972 views Asked by At

Is there any way to configure a canActivate guard used in Angular's router?

Having this SessionGuard:

@Injectable()
export class SessionGuard implements CanActivate {

    public requireLeagues: boolean = true;

    constructor(private authService: AuthService, private session: SessionService, private router: Router) {
    }


    async canActivate(): Promise<boolean> {
        if (!this.authService.isLoggedIn) {
            return false;
        }

        await this.session.start();

        if (this.requireLeagues && (!this.session.leagues || this.session.leagues.length == 0)) {
            //Redirect to create league page
            this.router.navigate(['/create-league']);

            return false;
        } else {
            return true;
        }
    }
}

And this routes:

const routes: Routes = [
    {path: '', component: HomeComponent, canActivate: [AuthGuard, SessionGuard]},// <-- requireLeagues = false
    {path: 'login', component: LoginComponent},
    {path: 'leagues', component: [AuthGuard, SessionGuard]},
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

I would like to set requireLeagues to true or false depending on the route withouth having to create a new, different guard. Is this possible?

1

There are 1 answers

0
joh04667 On BEST ANSWER

Yes, the canActivate method gets passed the current ActivatedRouteSnapshot and the RouterStateSnapshot.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   this.requireLeages = route.params... // something from route
}

Here's the docs for ActivatedRouteSnapshot. It has a lot of useful properties, including a data property that you can use to store your own data to share between routes and services.