【发布时间】: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