如何在角度4中点击浏览器后退按钮提醒用户?
即使第一次加载页面, onpopstate
也会被调用
import { PlatformLocation } from '@angular/common';
constructor( private platformLocation: PlatformLocation) {
platformLocation.onPopState(() => {
console.log("onPopState called");
window.alert("your data will be lost");
})
}
答案 0 :(得分:3)
添加一个candeactivate guard
可以-停用-guard.service.ts
import {Observable} from 'rxjs';
import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
) : Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate();
}
}
路由设置中的
const route: Route = [
{path: '', component: AppComponent, canDeactivate: [CanDeactivateGuard]}
]
在提供者数组中的app.module中提供你可以取消激活警卫。
考虑以下组件,其中我有变量来检查更改已保存
export class AppComponent implements CanComponentDeactivate {
changesSaved = false;
onUpdateServer() {
this.changesSaved = true;
}
canDeactivate() {
if(this.changesSaved) {
return true;
} else {
return confirm('Do you want to discard changes');
}
}
}
答案 1 :(得分:0)
您可以在组件内部使用ngOnDestroy
。当组件被销毁时,它将自动被调用,然后您可以发出任何警告。