Ionic 我在第一次刷新时遇到了问题,主页中的crome警报弹出窗口没有显示-呈角形

tkqqtvp1  于 2022-12-09  发布在  Ionic
关注(0)|答案(1)|浏览(156)

第一件事,谢谢你的答复,我的最后一个问题
现在我面临的问题-虽然我登陆主页的第一次这个警报弹出是不工作的,如果我移动到应用程序里面,它的工作正常,但第一次在主页它不工作.下面是我的代码

@HostListener("window:beforeunload", 
["$event"]) 
unloadHandler(event: Event) {
let result = confirm("Changes 
you made may not be saved.");
if (result) {
  // Do more processing...
}
event.returnValue = false; // 
stay on same page

}

g0czyy6m

g0czyy6m1#

我有另一个办法,试一次-
首先创建一个名为confirmation.guard.ts的保护文件-

import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from 
'@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentCanDeactivate {
confirm: () => boolean;
}

@Injectable()
export class ConfirmationGuard implements 
CanDeactivate<CanComponentCanDeactivate> {
canDeactivate(
component: CanComponentCanDeactivate,
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean>| boolean{ 
  return component.confirm();
 }
}

然后在app.module.ts中导入ConfirmationGuard

import { ConfirmationGuard } from './guards/confirmation.guard';
@NgModule({
 providers: [ConfirmationGuard]
})
export class AppModule { }

在定义了组件工艺路线的工艺路线模块文件中-使用此ConfirmationGuard,在该组件上显示警报弹出窗口-

import { ConfirmationGuard } from './guards/confirmation.guard';

   const routes: Routes = [
   { path: 'your-path', component: YourComponent, canDeactivate: 
   [ConfirmationGuard] },
   ];

  @NgModule({
  providers: [ConfirmationGuard ],
  imports: [],
  exports: [RouterModule]
 })
 export class YourRoutingModule { }

然后实现CanComponentCanDeactivate,您希望在哪个组件中显示弹出窗口-

import { CanComponentCanDeactivate } from '../../../guards/confirmation.guard';
 
 export class YourComponent implements CanComponentCanDeactivate {
 successRedirect: boolean = false;

 //call confirm() function which have created in guard file
 confirm() {
   if (!this.successRedirect) {
     return confirm("Are you sure you want to navigate away ?")
   }
   else{
      return true;
   }
 }
}

我希望它会有所帮助。

相关问题