본문 바로가기

IT

[angular] authGuard, canActivate, canActivateChild

We can make the guard like this.

@Injectable() =>this is for authService
export class AuthGuard implements CanActivate, CanActivateChild {

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

canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if (authenticated) {
return true;
} else {
this.router.navigate(['/']);
}
}
);
}

canActivateChild(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
{
return this.canActivate(route, state);
}
}

canActivate and canActiveChild perform  similarly, we can know what is different from their name.


and register in module.


const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'users', component: UsersComponent, children: [
{ path: ':id/:name', component: UserComponent }
]},
{ path: 'servers', canActivateChild: [AuthGuard], component: ServersComponent, children: [
{ path: ':id', component: ServerComponent },
{ path: ':id/edit', component: EditServerComponent }
]},
{path: 'not-found', component: PageNotFoundComponent},
{path: '**', redirectTo: '/not-found'}
];

 

canActivateChild: [AuthGuard] => this is for only child route.


canActivate: [AuthGuard] => this is for whole route include child.


'IT' 카테고리의 다른 글

[angular] dynamic data with resolver  (0) 2018.03.29
[angular] passing static data to route.  (0) 2018.03.29
[angular] Outsourcing route config  (0) 2018.03.23
[angular] redirecting and wildcard  (0) 2018.03.23
[angular] Handling queryParams  (0) 2018.03.23