Angular
Search…
Guards

CanActivate

Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled. If any guard returns a UrlTree, the current navigation is cancelled and a new navigation begins to the UrlTree returned from the guard.
1
interface CanActivate {
2
canActivate(
3
route: ActivatedRouteSnapshot,
4
state: RouterStateSnapshot):
5
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
6
}
Copied!

Description

The following example implements a CanActivate function that checks whether the current user has permission to activate the requested route
1
class UserToken {}
2
class Permissions {
3
canActivate(user: UserToken, id: string): boolean {
4
return true;
5
}
6
}
7
8
@Injectable()
9
class CanActivateTeam implements CanActivate {
10
constructor(private permissions: Permissions, private currentUser: UserToken) {}
11
12
canActivate(
13
route: ActivatedRouteSnapshot,
14
state: RouterStateSnapshot
15
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
16
return this.permissions.canActivate(this.currentUser, route.params.id);
17
}
18
}
Copied!

How to implement a Guard?

Here, the defined guard function is provided as part of the Route object in the router configuration:
1
content_copy@NgModule({
2
imports: [
3
RouterModule.forRoot([
4
{
5
path: 'team/:id',
6
component: TeamComponent,
7
canActivate: [CanActivateTeam]
8
}
9
])
10
],
11
providers: [CanActivateTeam, UserToken, Permissions]
12
})
13
class AppModule {}
Copied!