如何在角度4中单击浏览器后退按钮时提醒用户? [英] how to alert user on click of browser back button in angular 4?
本文介绍了如何在角度4中单击浏览器后退按钮时提醒用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在单击角度4中的浏览器后退按钮时提醒用户?
how to alert the user on click of browser back button in angular 4?
onpopstate
即使在页面首次加载时也会被调用
onpopstate
gets called even when the page loads for the first time
import { PlatformLocation } from '@angular/common';
constructor( private platformLocation: PlatformLocation) {
platformLocation.onPopState(() => {
console.log("onPopState called");
window.alert("your data will be lost");
})
}
推荐答案
添加可以取消激活的防护功能
Add a candeactivate guard
can-deactivate-guard.service.ts
can-deactivate-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中提供可以停用警卫的功能.
Provide your can Deactivate guards in your app.module in providers array.
考虑以下组件,我可以在其中检查已保存的更改
Consider the following component where I have variable to check changes Saved
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');
}
}
}
这篇关于如何在角度4中单击浏览器后退按钮时提醒用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文