我想在点击路由器链接后添加对话窗口,是和否答案,如果选择是,我们通过canActivate后卫。
但是在我们改变路线并且再次带着警卫来到那个路由器后,我们状态将被保存,无论我们在对话窗口中选择什么,我们可以在对话窗口中选择答案之前通过警卫。如何解决?
警卫服务
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;
}
}
你也将无法从result
内部返回时尚的subscribe()
。有关此问题,请参阅以下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();
}
}
希望这有帮助!