Angular - 如何根据用户角色重定向到仪表板

Angular - How to redirect to Dashboard based on user role

我有一个项目,ASP.NET Core 作为后端,Angular-13 作为前端。

当用户成功登录时,我在 POSTMAN 上收到以下响应:

{
   "status_code": 200,
   "message": "Successfully Logged In",
   "result": {
       "token": "gggggffffffffffffdddddddddddd",
       "user": {
           "id": 3,
           "user_name": "smith",
           "last_login": "2022-01-03T12:35:26.0305649"
          },
       "roles": [
           "Teacher"
       ],
   }
}

这是 Angular 代码:

user.ts:

export interface IResponse<T> {
  message: string;
  error: boolean;
  code: number;
  results: T;
}

export interface IUser {
  userName?: string;
  lastLogin?: Date;
  token?: string;
  roles?: string[];
  expires?: Date;
}

auth.service.ts:

export class AuthService {
  baseUrl = environment.apiUrl;
  private currentUserSource = new ReplaySubject<IUser>(1);
  currentUser$ = this.currentUserSource.asObservable();

  constructor(private http: HttpClient, private router: Router) { }

  login(model: any){
    return this.http.post(this.baseUrl+'auth/login', model).pipe(
      map((res: IUser)=>{
        const user = res;
        if(user){
          this.setCurrentUser(user);
        }
      })
    )
  }

  setCurrentUser(user: IUser){
    if(user){
      user.roles = [];
      const roles = this.getDecodedToken(user.token).role;//copy token to jwt.io see .role
      Array.isArray(roles) ? user.roles = roles : user.roles.push(roles);
      localStorage.setItem('user', JSON.stringify(user));
      this.currentUserSource.next(user);
    }
  }

  getDecodedToken(token: string) {
    return JSON.parse(atob(token.split('.')[1]));
  }
}

在 Angular 前端,我有两个仪表板:教师仪表板和学生仪表板

auth.component:

createForm() {
  this.loginForm = new FormGroup({
    UserName: new FormControl('', Validators.required),
    Password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(80)])
  })
}

login(){
  this.authService.login(this.loginForm.value).subscribe(res=>{
    this.router.navigateByUrl('/');
  }, error=>{
    this.toastr.error(error.error);
  })
}

如果用户成功登录。如果用户的角色是教师,它应该重定向到教师仪表板,如果角色是学生,它应该重定向到学生仪表板。

如何实现?

谢谢

首先,你可能想使用守卫

ng g guard isTeacher

ng g guard isStudent

对于每个守卫,注入一个服务,然后根据逻辑return true false。

如果在路由上使用组件,请使用 canActivate。

如果您使用 loadChildren,请使用 canLoad。

{
    path: '/teacher',
    canLoad: [isTeacher],
    loadChildren: () => import('teacher.module').then(m => m.somethingmodule),
  }

{
    path: '/teacher',
    canActivate: [isTeacher],
    component: teacherComp,
  }

学生也一样。

为什么要使用守卫?因此,如果您是学生,则不会误导航或查看教师组件。它仍然可以被绕过,因为它都是前端但仍然。