如果页面仍在加载,则Angular router.navigateByUrl()无效

时间:2018-03-03 02:46:12

标签: angular auth0

我正在尝试将auth0集成到我的角度应用中。

Auth0登录事件流程如下所示。

  1. Angular页面显示auth0登录窗口小部件(显示登录窗口小部件的代码位于服务中:AuthService)。

  2. 用户从登录小部件中选择身份验证提供程序(例如:使用google登录)。

  3. 浏览器会重定向到身份验证提供程序。

  4. 用户在身份验证提供程序中输入凭据。

  5. 浏览器会重定向回角网站,并重定向到已配置的回调网址。就我而言,这是一个显示加载指示的页面(因为登录仍未完成)。

  6. 使用身份验证令牌从auth0登录窗口小部件触发回调事件。

  7. 在回调中,进行REST调用以获取有关用户的更多信息。

  8. 当REST调用完成后,在将检索到的用户信息保存到本地存储后,将调用router.navigateByUrl('/home')返回主页。

  9. 但是,当我拨打router.navigateByUrl('/home')时,导航不会发生。但是,如果我在大约5秒钟超时后调用router.navigateByUrl('/home'),则导航成功。我怀疑导航发生时,浏览器加载应该在navigateByUrl()调用时完成。

    有没有人知道如何在不使用超时的情况下可靠地进行导航?

    以下是AuthService代码。

    @Injectable()
    export class AuthService {
        lock = new Auth0Lock(
            'my_client_id',
            'my_auth0_sub_domain',
            {
                auth: {
                    redirectUrl: window.location.origin + '/auth_loading',
                    responseType: 'token',
                    scope: 'openid'
                }
            }
        );
    
        userProfile: Object;
    
        constructor(public router: Router) {
            this.userProfile = JSON.parse(localStorage.getItem('profile'));
            this.lock.on("authenticated", (authResult: any) => {
                localStorage.setItem('id_token', authResult.idToken);
                this.lock.getProfile(authResult.idToken, (error: any, profile: any) => {
                    if (error) {
                        alert(error);
                        return;
                    }
                    localStorage.setItem('profile', JSON.stringify(profile));
                    this.userProfile = profile;
                    setTimeout(() => {
                        this.router.navigateByUrl('/home'); //This only works because of the timeout
                    }, 5000);
                });
            });
        }
    
        public login() {
            this.lock.show();       //This shows the auth0 login widget
        }
    }
    

1 个答案:

答案 0 :(得分:0)

我将auth0-lock从v10升级到了v11,现在它没有问题。