问题描述
我有带有 canActivate: [ AuthGuard ]
和 AuthGuard
如何在同一个路由器url中强制检查canActivate
?
How to force check canActivate
in same router url ?
例如:当前路由是 /admin
并且我有类似 session expired
的事件.我在 AuthGuard
中有会话检查,但只有当我执行 .navigate(...)
时,这个检查才会激活.如何在同一位置强制运行 canActivate
?
For example: Current route is /admin
and I have got event like session expired
. I have session check in AuthGuard
but this check activates only when I execute .navigate(...)
. How to force run canActivate
in same location?
我已经尝试过:this.router.navigate([ this.router.url ]);
但是 angular 检查相同的位置并且什么都不做.
I've tried: this.router.navigate([ this.router.url ]);
but angular checks same location and do nothing.
附言当我收到 session expired event
时,我可以定位到登录页面"或其他页面,但我在 AuthGuard
内有所有重定向,我不想在其中重复相同的重定向所有其他事件,我需要像 location.reload()
但在 Angular2 路线中.
p.s. I can locate to "login page" or other pages when I got session expired event
, but I have all redirects inside AuthGuard
and I do not want to repeat the same redirects in all other events, I need just like location.reload()
but in Angular2 routes.
主要问题听起来像:如何在当前位置强制重新运行 canActivate
守卫?
Main question sounds like: How to force rerun canActivate
guards in current location?
推荐答案
我的临时解决方案:
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
.
这篇关于Angular2:如何“重新加载"带路由器的页面(重新检查 canActivate)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!