2

有什么方法可以配置canActivateAngular 路由器中使用的守卫吗?

有这个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;
        }
    }
}

而这条路线:

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 {
}

我想requireLeagues根据路线设置为真或假,而不必创建一个新的、不同的警卫。这可能吗?

4

1 回答 1

1

是的,该canActivate方法通过 currentActivatedRouteSnapshotRouterStateSnapshot.

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

这是 ActivatedRouteSnapshot 的文档。它有很多有用的属性,包括data可以用来存储自己的数据以在路由和服务之间共享的属性。

于 2017-05-16T17:03:26.167 回答