首页 文章

Angular2:路由器事件:Route Guard解决之前的NavigationCancel

提问于
浏览
0

我有一个应用程序,其路由由AuthGuard保护,实现CanActivate . 可以激活检查以查看用户是否已登录,然后在返回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调用内返回其结果 .

1 回答

  • -1

    如果有其他人遇到这个问题,我通过用以下内容替换 else 块(以 *****HERE****** 开头)的内容解决了这个问题:

    return this.authService.setConfig()
                        .map(
                        config => {
                            // SET CONFIG VARIABLES
                            console.log("Config variables set");
    
                            // allow route access
                            return true;
                        })
                        .catch(err => {
                            console.error(err);
                            this.router.navigate(['/Login']);
                            return Observable.of(false);
                        });
    

相关问题