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,从而防止用户离开该组件页面。 确认方法返回了一个布尔值,表示用户是否

相关内容

热门资讯

透视ai!wpk辅助器,aap... 透视ai!wpk辅助器,aapoker透视脚本,透牌教程(原先是真的有挂);原来确实真的有挂(需添加...
透视ai代打!hhpoker辅... 透视ai代打!hhpoker辅助软件下载,hhpoker外挂靠谱吗,2025版教程(一向存在有挂);...
透视数据!aapoker辅助工... 透视数据!aapoker辅助工具存在吗,xpoker辅助工具,力荐教程(起初真的是有挂);(需添加指...
透视透视!hhpoker透视脚... 透视透视!hhpoker透视脚本视频,hhpoker俱乐部是干嘛的,解密教程(原来真的有挂)1、不需...
透视苹果版!wpk透视辅助,w... 透视苹果版!wpk透视辅助,wepoker辅助是真的假的,扑克教程(总是存在有挂)1、玩家可以在wp...
透视透视挂!智星德州辅助译码插... 透视透视挂!智星德州辅助译码插件靠谱吗,智星菠萝可以辅助吗,科技教程(竟然存在有挂)1、让任何用户在...
透视脚本!wepoker透视脚... 透视脚本!wepoker透视脚本安卓,hh poker辅助有用吗,可靠教程(都是是有挂);玩家在we...
透视肯定!wepoker免费透... 透视肯定!wepoker免费透视脚本,aapoker怎么选牌,扑克教程(素来是有挂);wepoker...
透视肯定!德普之星怎么作弊,w... 透视肯定!德普之星怎么作弊,wepoker透视app下载,系统教程(真是是真的有挂);支持2-10人...
透视脚本!wepoker辅助透... 透视脚本!wepoker辅助透视软件,pokemmo辅助官网,2025新版(竟然真的是有挂)1、不需...