Angular 2 Router Guards命令 [英] Angular 2 Router Guards order

查看:70
本文介绍了Angular 2 Router Guards命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在数组中定义角度2路由器防护.例如:

Angular 2 router guards can be defined in an array. for example:

<code>
 canActivate: ['CanAlwaysActivateGuard','AuthGuard']
</code>

以下是我的问题:

  1. 两个守卫的执行顺序是什么.
  2. 如果我只想在CanAlwaysActivateGuard返回true时才执行AuthGuard,那将是可能的.

推荐答案

我遇到了这个问题,并在寻找答案时碰到了您的帖子.一无所获-今天有时间-我想出了一个我认为您可能会感兴趣的解决方案.我创建了一个"CompositeRouteGuard":

I had this problem and came across your post in my search for answers. Finding none -- and having some time today -- I came up with a solution I thought you might be interested in. I created a "CompositeRouteGuard":

import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import {Injectable, Injector} from '@angular/core';
import { Observable } from "rxjs";

@Injectable()
export class CompositeRouteGuard implements CanActivate {

  constructor(  protected router: Router,
                protected injector: Injector ) {
  }

  canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> {
    var compositeCanActivateObservable: Observable<boolean> = Observable.of(true);

    let routeGuards = route.data.routeGuards;

    if(routeGuards){
      for( var i = 0; i < routeGuards.length; i++ ){
        let routeGuard = this.injector.get(routeGuards[i]);
        let canActivateObservable = routeGuard.canActivate(route, state);
        compositeCanActivateObservable = compositeCanActivateObservable.flatMap( (bool) => {
          if(!bool){
            return Observable.of(false);
          }
          else{
            return canActivateObservable;
          }
        });
      }
    }

    return compositeCanActivateObservable;
  }
}

这需要在route.ts中进行一些额外的配置.您需要在路由的数据元素中添加"routeGuards"数组.

That requires a little extra configuration in your routes.ts. You need to add a "routeGuards" array to the data element of the route.

const routes: Routes = [
  {
    path: '...',
    component: AComponent,
    data: { routeGuards: [ FooRouteGuard, BarRouteGuard, BazRouteGuard ] },
    canActivate: [ CompositeRouteGuard ]
  },
...

我只关心canActivate动作,但是您应该可以轻松地扩展它,例如,如果需要,可以说"canDeactivate".

I only cared about the canActivate action, but you should be able to easily extend this, to say "canDeactivate" (for example) if you need to.

现在,我的路由守卫以和"语义按顺序"运行(必须全部成功才能激活路由).

Now my route guards run "in order" with "and" semantics (all must succeed for route to be activated).

这篇关于Angular 2 Router Guards命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆