Angular RouteGuard /动态导航

时间:2018-08-06 22:20:53

标签: angular angular-ui-router

我有一个应用程序,其中导航栏会根据其所在产品的“区域”进行更改。我正在使用Angulars Route Guards来确保已检查其访问权限,因此他们只能访问其有权访问的路线。这很棒!

在我的app-routing-module.ts中,我(尝试)变得聪明,并利用ActivatedRouteSnapshot获取所有子链接,然后为其构建导航。我还想使用Route Guard来决定是否应该显示子链接。

//守卫

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { environment } from '../../environments/environment';
import { MeService } from '../shared/services/me.service';

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private _meService: MeService) {}
  async canActivate(
    next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    const user = await this._meService.getCurrentUser();
    if (user && user.isUserAdminForCompany) {
      return true;
    } else {
      return false;
    }
  }
}

//路线

export const routes: Routes = [
  { path: '', redirectTo: 'route1', pathMatch: 'full' },
  { path: 'route1', component: MyComponent,
    children: [
      { path: '', redirectTo: 'overview', pathMatch: 'full' },
      { path: 'overview', component: Overview },
      { path: 'specs', component: Specs, canActivate: [ AdminGuard ] }
    ]
  }
];

因此,一旦有人点击MyComponent,我将获取子路径并从中创建一个导航栏。如果AdminGuard返回false,是否可以使用某种指令或某种形式来利用/spec路径上的AdminGuard来隐藏URL?由于我的一些/更多防护人员需要对服务器的某种异步调用或某些其他服务依赖性,所以我不能只是在guard.canActivate之内调用*ngIf之类的东西。

我很确定它不存在,但似乎需要这样的设置:

<a [routerLink]="child.path" [canActivate]="child.guards">{{child.name}}</a>

更新 我最终只是在角度仓库上打开了GitHub Feature Request。似乎不存在此功能(以开箱即用的方式)。在找到更好的解决方案之前,我将要创建一个自定义指令,该指令将运行Guards中的逻辑以评估是否应该公开某些内容。

https://github.com/angular/angular/issues/25342

2 个答案:

答案 0 :(得分:0)

为什么不将以下代码添加到一个函数中,然后将该函数传递给* ngIf并传递给您具有routerLinks的相同组件。

const user = await this._meService.getCurrentUser();
if (user && user.isUserAdminForCompany) {
  return true;
} else {
  return false;
}

那将解决您的问题。只是稍微改变一下方法,这将隐藏路由器链接本身

答案 1 :(得分:0)

这就是我最终所追求的。由于没有任何“开箱即用”的方式来利用警卫人员来执行我想做的事情,所以我只是制定了一个自定义指令。

关于此解决方案,我要注意的一件事是,我讨厌以下两项(最终会更改)。

  1. 如果您的后卫有任何可以重定向的内容,则必须对其进行更改,以便后卫仅返回true / false。如果它在Guard失败时重定向页面,那么该指令将最终重定向您,而不是仅隐藏元素

  2. this._elementRef.nativeElement.style.display = hasAccess ? 'block' : 'none';有一个比仅执行简单隐藏更好的解决方案。它应该像*ngIf一样工作,除非它的值为true,否则根本不会渲染该元素。

实施:

<div appGuard [guards]="myGuardsArray">Something you want to hide .... </div>

指令:

import { Directive, ElementRef, Injector, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Directive({
  selector: '[appGuard]'
})
export class GuardDirective implements OnInit {
  @Input() guards: any[];
  private readonly _elementRef: ElementRef;
  private readonly _activatedRoute: ActivatedRoute;
  private readonly _router: Router;
  private readonly _injector: Injector;
  constructor(_elementRef: ElementRef, _activatedRoute: ActivatedRoute, _router: Router,
              _injector: Injector) {
    this._elementRef = _elementRef;
    this._activatedRoute = _activatedRoute;
    this._router = _router;
    this._injector = _injector;
  }
  async ngOnInit(): Promise<void> {
    const canActivateInstances = this.guards.map( g => this._injector.get(g));
    const results = await Promise.all(canActivateInstances.map( ca => ca.canActivate(this._activatedRoute.snapshot, this._router.routerState.snapshot)));
    const hasAccess = results.find( r => !r) === false ? false : true;
    this._elementRef.nativeElement.style.display = hasAccess ? 'block' : 'none';
  }
}

更新

一种简单的解决方案,弄清楚如何处理重定向:

async canActivate(
    next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    const user = await this._meService.getCurrentUser();
    const result = user && user.isUserAdminForCompany;
    if (next.routeConfig && next.routeConfig.canActivate.find( r => r.name === 'NameOfGuard') && !result) {
  window.location.href = `${environment.webRoot}/sign-in`;
}
    return result;
  }
相关问题