Angular CanActivate with登录对话框 [英] Angular CanActivate With Login Dialog

查看:128
本文介绍了Angular CanActivate with登录对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AuthGuard,我想在其中使用登录material2对话框.因此,在canActivate返回之前,将显示登录对话框,如果登录成功,则该对话框将返回true,因此canActivate也将返回true.如果登录失败,则对话框不返回任何内容,然后重试.

I have an AuthGuard in which I want to use a login material2 dialog with it. So before canActivate returns, the login dialog is shown and if the login is successful then the dialog returns true so then canActivate returns true as well. If the login is not successful, then the dialog does not return anything and tries again.

我已经在component中实现了该对话框,并且可以正常工作,我正在寻求有关如何将其与canActivate保护器集成的帮助.

I have already implemented the dialog in a component and its working fine, I'm looking for help on how to integrate it with the canActivate guard.

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private authService: AuthService, 
            private dialog: MatDialog,
            private router: Router) {}

    successfulLogin: boolean;

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

       // Open the Dialog
       let dialogRef = this.dialog.open(LoginDialog, {
            width: '450px',
            data: { success: this.successfulLogin }
        });

        // NEED HELP HERE, UNSURE HOW TO RETURN
        return dialogRef.afterClosed().subscribe(result =>{
            return result;
        })
    }
}

subscribe中的result正在返回true,但是我不确定如何正确地从canActivate返回的逻辑.上面的代码给出了以下错误声明.

The result from the subscribe is returning true but I am unsure about the logic on how to return from canActivate properly. The code above gives the following error statement.

不能将类型'Subscription'分配给类型'boolean | 可观察承诺'.类型订阅"不是 可分配给类型"Promise". 订阅类型中缺少属性'then'.

Type 'Subscription' is not assignable to type 'boolean | Observable | Promise'. Type 'Subscription' is not assignable to type 'Promise'. Property 'then' is missing in type 'Subscription'.

推荐答案

请改用toPromise方法

return dialogRef.afterClosed().toPromise().then(result =>{
    return result ? true : false;
});

这篇关于Angular CanActivate with登录对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆