基于角色的 Angular 路由

标签 angular angular2-routing

我正在使用 Angular,这是为了我的身份验证检查:

export class EnsureAuthenticated implements CanActivate {
    constructor(private auth: AuthService, private router: Router) {}
    canActivate(): boolean {
        if (localStorage.getItem('token')) {
            return true;
        }
        else {
            this.router.navigateByUrl('/login');
            return false;
        }
    }
}    

{ 
    path: 'path', 
    component: myComponent,
    canActivate: [EnsureAuthenticated]
}

它工作正常,但我的问题是用户和管理员都可以访问此页面。

我知道我没有对此设定任何条件。如何为其设置适当的条件?

我不想以管理员身份访问此页面

最佳答案

请参阅 stackblitz 中的此示例

在你的app-routing.module.ts中

const routes: Routes = [
   {
       path: "admin",
       component: AdminOnlyComponent,
       canActivate: [RoleGuardService],
       data: { roles: ['admin']}
   },
   ...
}

在您的 RoleGuardService 中

import { Injectable } from '@angular/core';
import { UserRolesService} from './user-roles.service';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
  providedIn: 'root'
})
export class RoleGuardService {

  constructor(private getUserRoles: UserRolesService) { }

  canActivate(route: ActivatedRouteSnapshot): boolean {
    return route.data.roles.some( ai => this.getUserRoles.getRoles().includes(ai) );
  }
}

在 UserRolesService 中

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserRolesService {
   userRoles: string[] = [];

  constructor() { }

  setRoles(Roles: string[]){
    this.userRoles = Roles.slice(0);
  }

  getRoles(){
    return this.userRoles;
  }
}

当用户登录系统时设置 Angular 色或从本地存储获取这些 Angular 色......

关于基于角色的 Angular 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536856/

相关文章:

angular2-routing - RC6 升级的子路由错误

javascript - Angular 更新表单填充输入字段,但仍然在控制台中返回错误?

javascript - Angular 2 - 无法匹配任何路由 'auth'

Angular 2 : Route generator for '...' was not included in parameters passed

angular - PrimeNg 上下文菜单传递数据问题

angular - 无法绑定(bind)到 'routerLink',因为它不是 'a' 的已知属性。尽管引用了路由器模块,但还是有错误

Angular 路由器 v3 : targeting named outlet

css - 如何设置工具提示的样式?

javascript - Angular 选择选项时更改 src 属性

angular - typescript 中的变量类型验证不起作用