【问题标题】:How can I protect a URL based on the input of an Angular Material Dialog using a Guard?如何使用 Guard 根据 Angular Material Dialog 的输入来保护 URL?
【发布时间】:2018-05-24 13:52:42
【问题描述】:

目标:

我有一个使用 Guard 保护的特定 URL。当用户尝试访问该 URL 时,我会打开一个 Angular 4 材质对话框。根据对话框输入,我想授权或不授权用户。

问题:

在 Guard 中,我订阅了对话框。关闭时,我收到对话框输入。当用户尝试访问 URL 时,canActivate 会自动评估为 false,而无需等待用户输入。 也就是说,modal被订阅了,但是马上返回false,因为函数没有等待对话框关闭。

问题:

如何根据用户输入授权或不授权用户访问 URL?

后卫:

    @Injectable()
    export class VerificationGuard implements CanActivate {

      pwd: string;
      auth: boolean;

      constructor(private dialog: MatDialog) {
      }

      public canActivate() {
        const dialog = this.dialog.open(VerificationDialogComponent);
        dialog.afterClosed()
          .subscribe(val => {
            if (val) {
              this.pwd = val;
              return true;
            }
          });
        return false;
      }
    }

对话框:

    import { Component, OnInit } from '@angular/core';
    import { MatDialogRef } from '@angular/material';

    @Component({
      selector: 'app-verification-dialog',
      templateUrl: './verification-dialog.component.html',
      styleUrls: ['./verification-dialog.component.scss']
    })
    export class VerificationDialogComponent implements OnInit {

      pwd: string;

      constructor(public dialogRef: MatDialogRef<VerificationDialogComponent>) { }

      ngOnInit() {
      }

      /**
       * Close dialog and pass back data.
       */
      confirmSelection() {
        this.dialogRef.close(this.pwd);
      }
    }

【问题讨论】:

  • 为什么不把 return false 放在回调里面呢?另外,您不能从subscribe 返回,请改用map
  • 在回调中返回 false 不起作用。此外,您不能映射订阅。
  • not work 是什么意思?好吧,它可能不起作用,因为您正试图从订阅返回,这是不可能的。

标签: angular angular-material angular-guards


【解决方案1】:

考虑使用服务来存储标志,而不是从 VerificationGuard 打开此模式。

@Injectable()
export class AuthService {
  isLoggedIn = false;
}

该服务不会让您登录,但它有一个标志来告诉您用户是否已通过身份验证。

从你的警卫那里呼叫它:

@Injectable()
export class VerificationGuard implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.authService.isLoggedIn)
  }
}

将模态逻辑重新定位到发出路由器导航事件的位置,并让它在提交凭据时执行以下操作:

  1. AuthService.isLoggedIn 设置为true
  2. 发出路由器导航事件。
  3. AuthService.isLoggedIn 设置为false 从守卫。

AuthService.isLoggedIn 应重置为 false,canActivate() 应返回 true。

请参阅“Teach AuthGuard 进行身份验证”下的 https://angular.io/guide/router#canactivatechild-guarding-child-routes 了解类似示例。

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2012-08-14
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2010-12-14
    • 2015-06-16
    相关资源
    最近更新 更多