【发布时间】:2018-03-03 08:57:47
【问题描述】:
我有一个应用程序,其路由由实现 CanActivate 的 AuthGuard 保护。可以激活检查以查看用户是否已登录,然后在返回 true 或 false 之前检查是否设置了配置变量。如果用户已登录但尚未发送配置变量,则 AuthGuard 会进行 http 调用以检索配置设置,并在 http 调用无错误解决后返回 true(否则为 false)。
问题是路由器在配置调用解决之前取消导航到请求的路由。
下面是AuthGuard的canActivate方法:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let authenticated = this.isAuthenticated();
if (authenticated) {
console.log("User authenticated, checking for configs...");
if (this.config.defined) {
console.log("Config defined!");
return true;
} else {
***** HERE ******
console.log("Config not defined, setting configs...");
this.authService.setConfig()
.take(1)
.subscribe(
config => {
// SET CONFIG VARIABLES
console.log("Config variables set");
// allow route access
return true;
},
err => {
console.error(err);
this.router.navigate(['/Login']);
return false;
}
);
this.router.navigate(['/Login']);
return false;
}
} else {
console.log("User not authenticated, back to login");
this.router.navigate(['/Login']);
return false;
}
}
因此,当我登录并且尝试访问页面时未设置配置变量(即,我在由**** HERE **** 表示的逻辑块中),我在控制台中看到:
Setting config...
NavigationCancel {id: 1, url: "/", reason: ""}
NavigationStart {id: 2, url: "/Login"}
RoutesRecognized {id: 2, url: "/Login", urlAfterRedirects: "/Login", state: RouterStateSnapshot}
NavigationEnd {id: 2, url: "/Login", urlAfterRedirects: "/Login"}
Config variables set
在 AuthGuard 配置 http 调用有机会解决之前,导航被取消并且路由器重定向,就好像 AuthGuard 返回 false 一样。我想找到一种方法让 AuthGuard 在解决其中的 http 调用时返回其结果。
【问题讨论】:
标签: javascript angular typescript routing routes