0

嗨 Angular 开发人员,

请我需要您的帮助,我需要阻止具有特定角色的路由,这是我的带有配置文件的文档:

在此处输入图像描述

我的角度守卫返回并反对配置文件:{admin:true,current:false}

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class RoleGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<any> | boolean {

    return this.authService.getAuthWithProfile().pipe(
      map((data) => {
        const roles = data.roles;
        return roles; // This returns   {admin: true, current: false}
      })
    );

   }
  }

问题是如何在 Angular 路由中实现角色保护,例如:

{ path: 'tasks', component: TasksComponent, canActivate: [RoleGuard] },
4

1 回答 1

1

一种方法是使用Routedata的属性。您可以将自定义值附加到任何给定的路由。在您的示例中,您可以创建一个名为的属性,该属性可以在您的. 在以下示例中,将一组角色添加到 TasksComponent 的路由中。在警卫中,我们可以从中提取检查从 Firebase 返回的角色是否存在且处于活动状态:rolescanActivate()rolesnext.data.roles

路线:

{
  path: 'tasks',
  component: TasksComponent,
  data: {
    roles: ['admin', 'subscriber']
  }
  canActivate: [RoleGuard]
}

警卫:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | boolean {
  const routeRoles = next.data && next.data.roles; // ['admin', 'subscriber']

  return this.authService.getAuthWithProfile().pipe(
    map((data) => {
      const roles = data.roles; // { admin: true, current: false }
      const activeRoles = Object.entries(roles).filter(([role, isActive]) => isActive).map(([role, isActive]) => role); // ['admin']

      return routeRoles.some(routeRole => activeRoles.includes(routeRole)); // true
    })
  );

  }
}

data.roleson the route 不必是一个数组,它可以是一个对象,您可以以您喜欢的任何方式检查激活的路线的存在。例如,如果只有一个角色:

{
  path: 'tasks',
  component: TasksComponent,
  data: {
    role: 'admin'
  }
  canActivate: [RoleGuard]
}

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | boolean {
  const routeRole = next.data && next.data.role; // 'admin'

  return this.authService.getAuthWithProfile().pipe(
    map((data) => {
      const roles = data.roles; // { admin: true, current: false }
      const activeRoles = Object.entries(roles).filter(([role, isActive]) => isActive).map(([role, isActive]) => role); // ['admin']

      return routeRoles.includes(routeRole); // true
    })
  );

  }
}

希望这会有所帮助!

于 2019-10-02T14:11:42.393 回答