为了涵盖针对浏览器刷新、关闭窗口等的防护(有关该问题的详细信息,请参阅@ChristopheVdal对Günter回答的 comments ),我发现在您的类的canDeactivate
实现中添加@HostListener
修饰符来监听beforeunload
window
事件会很有帮助.如果配置正确,这将同时防止应用内导航和外部导航.
例如:
Component:个
import { ComponentCanDeactivate } from './pending-changes.guard';
import { HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export class MyComponent implements ComponentCanDeactivate {
// @HostListener allows us to also guard against browser refresh, close, etc.
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
// insert logic to check if there are pending changes here;
// returning true will navigate without confirmation
// returning false will show a confirm dialog before navigating away
}
}
Guard:
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
// if there are no pending changes, just allow deactivation; else confirm first
return component.canDeactivate() ?
true :
// NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
// when navigating away from your angular app, the browser will show a generic warning message
// see http://stackoverflow.com/a/42207299/7307355
confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
}
}
Routes:
import { PendingChangesGuard } from './pending-changes.guard';
import { MyComponent } from './my.component';
import { Routes } from '@angular/router';
export const MY_ROUTES: Routes = [
{ path: '', component: MyComponent, canDeactivate: [PendingChangesGuard] },
];
Module:
import { PendingChangesGuard } from './pending-changes.guard';
import { NgModule } from '@angular/core';
@NgModule({
// ...
providers: [PendingChangesGuard],
// ...
})
export class AppModule {}
NOTE:正如@JasperRissee uw指出的,IE和Edge处理beforeunload
事件的方式与其他浏览器不同,当beforeunload
事件激活时(例如,浏览器刷新、关闭窗口等),IE和Edge将在确认对话框中包含单词false
.在Angular 应用程序内导航不受影响,并将正确显示您指定的确认警告消息.那些需要支持IE/Edge并且不希望false
在beforeunload
事件激活时在确认对话框中显示/希望显示更详细消息的用户,也可能希望查看@JasperRissee uw的解决方法答案.