Goal:
我有一个使用Guard保护的特定URL . 当用户尝试访问该URL时,我打开了Angular 4材质对话框 . 根据对话框输入,我想授权或不授权用户 .
Issue:
在Guard中我订阅了对话框 . 关闭时,我收到对话框输入 . 当用户尝试访问URL时,canActivate会自动评估为false,而不会等待用户输入 . 换句话说,模态是订阅的,但是会立即返回false,因为函数不会等待对话框关闭 .
Question:
如何根据用户输入授权或不授权用户访问URL?
Guard:
@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;
}
}
Dialog:
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);
}
}
1 回答
不要从VerificationGuard打开此模式,而是考虑使用服务来存储标志 .
该服务不会让您登录,但它有一个标志,告诉您该用户是否经过身份验证 .
从你的卫兵那里打电话:
将模态逻辑重定位到发出路由器导航事件的位置,并在提交凭据时执行以下操作:
将
AuthService.isLoggedIn
设为true
.发出路由器导航事件 .
从守卫处将
AuthService.isLoggedIn
设为false
.AuthService.isLoggedIn
应重置为false,canActivate()
应返回true .有关类似示例,请参阅_43366_下的https://angular.io/guide/router#canactivatechild-guarding-child-routes .