[英]Angular2: how to “reload” page with router (recheck canActivate)?
I have routers with canActivate: [ AuthGuard ]
and validation inside AuthGuard
我有带有canActivate: [ AuthGuard ]
和在AuthGuard
内AuthGuard
验证的AuthGuard
How to force check canActivate
in same router url ? 如何在同一路由器URL中强制检查canActivate
?
For example: Current route is /admin
and I have got event like session expired
. 例如:当前路由是/admin
,我有类似session expired
事件。 I have session check in AuthGuard
but this check activates only when I execute .navigate(...)
. 我在AuthGuard
进行了会话检查,但是只有当我执行.navigate(...)
时,该检查才会激活。 How to force run canActivate
in same location? 如何在同一位置强制运行canActivate
?
I've tried: this.router.navigate([ this.router.url ]);
我试过了: this.router.navigate([ this.router.url ]);
but angular checks same location and do nothing. 但是角度检查相同的位置却什么也不做。
ps 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. ps当我遇到session expired event
,我可以定位到“登录页面”或其他页面,但是我在AuthGuard
拥有所有重定向,并且我不想在所有其他事件中重复相同的重定向,我需要的是location.reload()
但在Angular2路线中。
Main question sounds like : How to force rerun canActivate
guards in current location? 主要问题听起来像是 :如何强制重新运行canActivate
警卫在当前位置?
My temporary solution: 我的临时解决方案:
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 app.routes.ts
{ path: 'faq', canActivate: [ AuthGuard ], component: FaqComponent },
{ path: 'about', canActivate: [ AuthGuard ], component: AboutUsComponent },
{ path: 'upgrade', canActivate: [ AuthGuard ], component: UpgradeComponent },
This code runs AuthGuard
again. 此代码再次运行AuthGuard
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.