在您的情况下,希望您在登录 api 响应中获得用户角色。您需要将用户重定向到他们角色的特定视图库。
login() {
this.authenticationService.login(this.email, this.password).subscribe((response: any) => {
this.authenticationService.getAccountData().subscribe((res: any) => {
this.authority = res.authorities[0]; // role
this.sharedService.setUserRole(this.authority);
if (this.authority === Role.ADMIN_ROLE) {
this.router.navigate(['admin/home']);
} else if (this.authority === Role.USER_ROLE) {
this.router.navigate(['user/home']);
}
});
});
}
要限制路由,您需要创建身份验证保护,您需要在其中实现逻辑来检查请求路由的角色。
import { Injectable } from '@angular/core';
import { Router, NavigationEnd, Route } from '@angular/router';
@Injectable()
export class AdminAuthGuardService {
constructor(
private sharedService: SharedService,
private router: Router
) { }
canActivate(route: Route): boolean {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (event.url === '/' || event.url === '/login') {
if (this.sharedService.getRole() === Role.ADMIN_ROLE) {
return true;
} else{
return false;
}
}
}
});
}
}
然后在你的路由文件中使用这个 AdmiAuthGuard
path: 'admin',
canActivate: [AdminAuthGuardService],
children: [
{
path: 'home',
loadChildren: '' // add chile module path
},
]