我的路由器带有canActivate: [ AuthGuard ]
并在AuthGuard
中进行了验证
如何在同一路由器URL中强制检查canActivate
?
例如:当前路线是/admin
,我有类似session expired
的事件。我在AuthGuard
中进行了 session 检查,但是只有当我执行.navigate(...)
时,此检查才会激活。如何强制在同一位置运行canActivate
?
我试过了:this.router.navigate([ this.router.url ]);
,但是angular检查相同的位置并且什么也不做。
p.s.当我收到session expired event
时,我可以定位到“登录页面”或其他页面,但是我在AuthGuard
中拥有所有重定向,并且我不想在所有其他事件中重复相同的重定向,我需要像location.reload()
一样,但是在Angular2 route 。
主要问题听起来像:如何强制在当前位置重新运行canActivate
防护程序?
最佳答案
我的临时解决方案:
auth.service.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);
}
}
}
app.routes.ts
{ path: 'faq', canActivate: [ AuthGuard ], component: FaqComponent },
{ path: 'about', canActivate: [ AuthGuard ], component: AboutUsComponent },
{ path: 'upgrade', canActivate: [ AuthGuard ], component: UpgradeComponent },
此代码再次运行
AuthGuard
。关于javascript - Angular2 : how to "reload" page with router (recheck canActivate)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45680250/