首页 > 解决方案 > Angular 12 - 根据角色重定向用户

问题描述

我有一个场景,管理员角色登录将有权访问 Home 和 UserView 组件。默认情况下,管理员将在登录后转到主页组件。用户角色登录只能访问 UserView 组件,登录后应重定向到 Userview 组件。

我使用过 canactivate 但对如何根据上述条件根据角色重定向用户感到困惑,将有 2 个主页(主页(用于管理员角色)和 UserView(用于用户角色)组件)。

标签: angular

解决方案


在您的情况下,希望您在登录 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
     },
]

推荐阅读