gpt4 book ai didi

angular - 如何在 Angular 4 中单击浏览器后退按钮时提醒用户?

转载 作者:行者123 更新时间:2023-12-02 18:36:52 25 4
gpt4 key购买 nike

如何在 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");
})
}

最佳答案

添加一个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]}
]

提供您可以在providers数组中的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');
}
}
}

关于angular - 如何在 Angular 4 中单击浏览器后退按钮时提醒用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48699611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com