Angular离开页面前的警告bug
创始人
2024-10-28 00:30:18
0

在需要进行路由守卫时,可以在路由配置文件中使用以下代码:

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

export interface ComponentCanDeactivate {
 canDeactivate: () => Observable | Promise | boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate {
 canDeactivate(component: ComponentCanDeactivate): Observable | Promise | boolean {
  return component.canDeactivate ? component.canDeactivate() : true;
 }
}

这将导出一个名为ComponentCanDeactivate的接口,它可以提供canDeactivate方法,并让路由守卫了解该组件中是否有该方法。通过该方法,我们可以在用户即将离开该组件或页面时通过返回一个布尔值或一个 Promise,来提供一个提示信息。例如,以下是一个示例组件:

import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-your-component',
 templateUrl: './your-component.component.html',
 styleUrls: ['./your-component.component.scss']
})
export class YourComponentComponent implements ComponentCanDeactivate, OnInit {
 formChanged = false;

 constructor() {}

 ngOnInit() {}

 canDeactivate(): Observable | Promise | boolean {
  if (this.formChanged) {  
   return confirm('You have unsaved changes. Are you sure you want to discard them?');
  }
  return true;
 }
}

如果用户在该组件中进行了更改,则该组件的formChanged属性将标记为 true。当用户即将离开该组件或页面时,我们将检查formChanged属性,如果已更改则弹出提示框来获取用户的意见。当用户单击 "是" 时,将返回 true,而如果用户点击 "否" 或 "取消" 按钮时,则返回 false,从而防止用户离开该组件页面。 确认方法返回了一个布尔值,表示用户是否

相关内容

热门资讯

4分钟辅助!wepoker底牌... 4分钟辅助!wepoker底牌透视,epoker底牌透视,经验教程(证实有挂)1、上手简单,内置详细...
第9分钟辅助!wepoker有... 第9分钟辅助!wepoker有脚本吗,wepoker轻量版透视方法,经验教程(真的有挂)1、每一步都...
第四分钟辅助!hhpoker德... 第四分钟辅助!hhpoker德州牛仔视频,hhpoker透视脚本视频,经验教程(有挂详情)1、hhp...
第4分钟辅助!wepoker一... 第4分钟辅助!wepoker一直输的号能继续打吗,wepoker怎么看牌型,策略教程(有挂细节)1、...
八分钟辅助!wepoker轻量... 八分钟辅助!wepoker轻量版透视系统,hhpoker辅助挂下载,法门教程(确实有挂)1、该软件可...
第2分钟辅助!werplan免... 第2分钟辅助!werplan免费挂下载,wepoker免费脚本,妙计教程(证实有挂)1)werpla...
五分钟辅助!哈糖大菠萝助手,h... 五分钟辅助!哈糖大菠萝助手,hhpoker软件安装包,教材教程(发现有挂)1、上手简单,内置详细流程...
第3分钟辅助!拱趴大菠萝作弊方... 第3分钟辅助!拱趴大菠萝作弊方法,xpoker辅助怎么用,手册教程(有挂透明挂)一、拱趴大菠萝作弊方...
两分钟辅助!poker辅助器免... 两分钟辅助!poker辅助器免费安装,hhpoker有没有外挂,大纲教程(有挂助手)1、很好的工具软...
第三分钟辅助!wpk透视怎么安... 第三分钟辅助!wpk透视怎么安装,hhpoker透视脚本视频,演示教程(有挂技巧)暗藏猫腻,小编详细...