Reputation: 29
I have a few components in my "shop-website". There is one component which should only be accessible for the Admin. In the local Storage there is a token isAdmin. I have now implemented that a special component is just shown in the home site when the admin is logged in. But id you enter the link of this component(http://localhost:4200/Authorize) it shows everyone. How can I implement that it should be accessible only for Admins.
Upvotes: 0
Views: 459
Reputation: 156
You have to use canActivate in your routes definition.
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
canActivate: [AuthGuard]
}
])
],
})
You can create custom conditions as AuthGuard:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
) {}
canActivate() {
if (somthing) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
Check the documentation https://angular.io/api/router/CanActivate
Upvotes: 1