如何使用模态窗口添加防护?
Posted
技术标签:
【中文标题】如何使用模态窗口添加防护?【英文标题】:How to add guard with modal window? 【发布时间】:2019-08-07 15:10:45 【问题描述】:我想添加对话窗口,有yes和no答案,在我们点击路由器链接后,如果选择yes,我们通过canActivate guard。
但是当我们改变路由并再次使用guard返回到那个路由器后,无论我们在对话窗口中选择什么,我们的状态都会被保存,并且我们可能会在对话窗口中选择答案之前通过保护。如何解决?
看守服务
import Injectable from '@angular/core';
import AuthService from './auth.service';
import ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot from '@angular/router';
import DialogWindowComponent from '../../Components/DialogWindow/dialog-window.component';
import MatDialog from '@angular/material/dialog';
@Injectable(
providedIn: 'root'
)
export class AuthGuardService implements CanActivate
result: boolean;
constructor(public dialog: MatDialog)
openDialog(): void
const dialogRef = this.dialog.open(DialogWindowComponent,
width: '250px',
);
dialogRef.afterClosed().subscribe(result =>
console.log('The dialog was closed');
console.log(result);
this.result = result;
);
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean
this.openDialog();
console.log('AuthGuard#canActivate called');
return this.result;
【问题讨论】:
【参考方案1】:您也无法从subscribe()
内部返回result
。有关此问题,请参阅以下related question。
话虽如此,尝试改为返回 Observable<boolean>
,因为 CanActivate 也可以为这些类型的异步操作返回 Observable<boolean>
:
import Injectable from '@angular/core';
import AuthService from './auth.service';
import ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot from '@angular/router';
import DialogWindowComponent from '../../Components/DialogWindow/dialog-window.component';
import MatDialog from '@angular/material/dialog';
import Observable from 'rxjs';
import map from 'rxjs/operators';
@Injectable(
providedIn: 'root'
)
export class AuthGuardService implements CanActivate
constructor(public dialog: MatDialog)
openDialog(): Observable<boolean>
const dialogRef = this.dialog.open(DialogWindowComponent,
width: '250px',
);
return dialogRef.afterClosed().pipe(map(result =>
// can manipulate result here as needed, if needed
// may need to coerce into an actual boolean depending
return result;
));
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean>
return this.openDialog();
希望对您有所帮助!
【讨论】:
谢谢,它的工作!如何守卫等待从openDialog返回?我的意思是,我们点击链接并打开模式,接下来会发生什么? 实际上 Angular 在继续导航之前正在等待Observable<boolean>
解析/发出,在这种情况下,当模态以某种方式关闭时。您需要确保从return dialogRef.afterClosed().pipe(map(
返回的结果是正确的true
或false
值。 true
将允许继续导航,false
将阻止导航。以上是关于如何使用模态窗口添加防护?的主要内容,如果未能解决你的问题,请参考以下文章