基于角色的重定向

Role based redirecting

我想根据用户的角色重定向用户。 F.e。当用户输入 'Teacher' 时,他被重定向到页面“1”;如果他以 'Student' 输入,他将被重定向到页面“2”。当用户仅输入 main url 'app.com' (F.e.)

时,它也必须工作
const routes: Routes = [
  {
    path: '',
    component: TesLandingPageContainer,
    canActivate: [AutheticatedGuard],
    canActivateChild: [UserRoleGuard],
    children: [
      {
        path: '',
        redirectTo: '/users/profile',
        pathMatch: 'full',
      },
  ...
  },          
  {
    path: '**',
    redirectTo: ''
  }
];

我有这个守卫

@Injectable()
export class AutheticatedGuard implements CanActivate {
  constructor(private store: Store<AppState>, private router: Router) { }

  canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(getIsAuthenticated),
      filter(isAuth => isAuth != null),
      tap(isAuth => {
        if (!isAuth) {
          this.router.navigate(['/login']);
        }
      }),
      take(1)
    );
  }
}

如果我这样写,它会循环

canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(getUserRoleAndAuth),
      filter(user => user.isAuth != null),
      tap(user => {
        switch (user.role) {
          case 'ADMIN': {
            this.router.navigate(['user/requests']);
            break;
          }
          case 'TEACHER': {
            this.router.navigate(['groups']);
            break;
          }
          case 'STUDENT': {
            this.router.navigate(['student']);
            break;
          }
          default: {
            this.router.navigate(['/login']);
          }
        }
      }),
      map(user => user.isAuth),
      take(1)
    );
    ```

而不是使用 this.router.navigate(['student']); 使用 return this.router.parseUrl('/student');

parseUrl 将创建 UrlTree,这有助于从 CanActivate.

导航应用程序

您需要 return 来自 CanActivate 接口的东西,布尔值或 UrlTree。

按照你的逻辑return要么是学生要么是老师URL。