如何在 angular 4 中点击浏览器后退按钮时提醒用户?
how to alert user on click of browser back button in angular 4?
如何在 angular 4 中点击浏览器后退按钮时提醒用户?
onpopstate
即使在页面第一次加载时也会被调用
import { PlatformLocation } from '@angular/common';
constructor( private platformLocation: PlatformLocation) {
platformLocation.onPopState(() => {
console.log("onPopState called");
window.alert("your data will be lost");
})
}
你可以在里面使用ngOnDestroy
,component.It会在组件要被销毁时自动调用,然后你可以发出任何警告。
添加一个 candeactivate 守卫
可以-停用-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 中提供你的 can Deactivate guards。
考虑以下组件,其中我有变量来检查已保存的更改
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');
}
}
}
如何在 angular 4 中点击浏览器后退按钮时提醒用户?
onpopstate
即使在页面第一次加载时也会被调用
import { PlatformLocation } from '@angular/common';
constructor( private platformLocation: PlatformLocation) {
platformLocation.onPopState(() => {
console.log("onPopState called");
window.alert("your data will be lost");
})
}
你可以在里面使用ngOnDestroy
,component.It会在组件要被销毁时自动调用,然后你可以发出任何警告。
添加一个 candeactivate 守卫
可以-停用-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 中提供你的 can Deactivate guards。
考虑以下组件,其中我有变量来检查已保存的更改
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');
}
}
}