Angular2:如何用路由器“重新加载”页面(重新检查canActivate)?

时间:2017-08-14 17:54:41

标签: javascript angular2-routing angular-cli

我有canActivate: [ AuthGuard ]的路由器和AuthGuard

内的验证

如何在同一路由器网址中强行检查canActivate

例如:当前路线为/admin,我有session expired之类的事件。我在AuthGuard进行了会话检查,但只有在执行.navigate(...)时才会激活此检查。如何强制在同一位置运行canActivate

我已经尝试过:this.router.navigate([ this.router.url ]);但角度检查相同位置并且什么也不做。

P.S。当我得到session expired event时,我可以找到“登录页面”或其他页面,但我在AuthGuard内有所有重定向,我不想在所有其他事件中重复相同的重定向,我需要像location.reload()但是在Angular2路线中。

主要问题听起来像:如何强制在当前位置重新运行canActivate警卫?

1 个答案:

答案 0 :(得分:3)

我的临时解决方案:

<强> auth.service.ts

#!C:\Python33\python.exe

<强> app.routes.ts

import { Injectable, Injector } from '@angular/core';
import { ActivatedRoute, Router, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthService {

  constructor(private route: ActivatedRoute,
              private router: Router,
              private injector: Injector) {
    this.forceRunAuthGuard();
  }

  // Dirty hack for angular2 routing recheck
  private forceRunAuthGuard() {
    if (this.route.root.children.length) {
      // gets current route
      const curr_route = this.route.root.children[ '0' ];
      // gets first guard class
      const AuthGuard = curr_route.snapshot.routeConfig.canActivate[ '0' ];
      // injects guard
      const authGuard = this.injector.get(AuthGuard);
      // makes custom RouterStateSnapshot object
      const routerStateSnapshot: RouterStateSnapshot = Object.assign({}, curr_route.snapshot, { url: this.router.url });
      // runs canActivate
      authGuard.canActivate(curr_route.snapshot, routerStateSnapshot);
    }
  }

}

此代码再次运行 { path: 'faq', canActivate: [ AuthGuard ], component: FaqComponent }, { path: 'about', canActivate: [ AuthGuard ], component: AboutUsComponent }, { path: 'upgrade', canActivate: [ AuthGuard ], component: UpgradeComponent },