【问题标题】:Angular 12 - Redirect users based upon rolesAngular 12 - 根据角色重定向用户
【发布时间】:2021-10-19 09:49:40
【问题描述】:

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

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

【问题讨论】:

  • 请分享您的auth guardrouting 代码。

标签: angular


【解决方案1】:

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

【讨论】:

  • 您好,我已经完成了上述操作,但问题是 UserView 没有按钮,当我们浏览 UserView 的直接 url 时,它会刷新页面三次然后加载它
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多