我的“商店网站”中有一些组件。只有一个组件只能由管理员访问。在本地存储中,有一个令牌isAdmin。现在,我已经实现了一个特殊的组件,当管理员登录后,该组件仅显示在主站点中。但是,如果您输入此组件的链接(http:// localhost:4200 / Authorize),它就会向所有人显示。如何实现仅管理员可以访问的功能。
答案 0 :(得分:1)
您必须在路线定义中使用canActivate。
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
canActivate: [AuthGuard]
}
])
],
})
您可以创建自定义条件作为AuthGuard:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
) {}
canActivate() {
if (somthing) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}