CanActivate

Interface that a class can implement to be a guard deciding if a route can be activated.

一个接口,某些类可以实现它以扮演一个守卫,来决定该路由能否激活。

interface CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean }

说明

class UserToken {} class Permissions { canActivate(user: UserToken, id: string): boolean { return true; } } @Injectable() class CanActivateTeam implements CanActivate { constructor(private permissions: Permissions, private currentUser: UserToken) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean>|Promise<boolean>|boolean { return this.permissions.canActivate(this.currentUser, route.params.id); } } @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamCmp, canActivate: [CanActivateTeam] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {}

You can alternatively provide a function with the canActivate signature:

你还可以转而实现一个带有 canActivate 签名的函数:

@NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamCmp, canActivate: ['canActivateTeam'] } ]) ], providers: [ { provide: 'canActivateTeam', useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true } ] }) class AppModule {}

方法

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean

参数

route

Type: ActivatedRouteSnapshot.

state

Type: RouterStateSnapshot.

返回值

Observable<boolean> | Promise<boolean> | boolean