본문 바로가기

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.