如何使用模态窗口添加防护?

时间:2019-03-16 20:30:48

标签: angular

我想添加一个对话框窗口,单击路由器链接后,是且没有答案,如果选择是,我们将通过canActivate 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 个答案:

答案 0 :(得分:2)

您也将无法从result内部返回subscribe()。有关此问题,请参见以下related question

话虽如此,请尝试改为将CanActivate返回Observable<boolean>,也可以针对这些类型的异步操作返回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();
    }
}

希望有帮助!