Angular - Sweetalrt2 在我点击“确定”之前进行重定向
创始人
2024-10-14 23:01:14
0

你可以使用Angular路由守卫来实现在点击“确定”之前进行重定向。下面是一个示例代码:

首先,创建一个名为confirm.guard.ts的路由守卫文件。

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

@Injectable({
  providedIn: 'root'
})
export class ConfirmGuard implements CanDeactivate {
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ): Observable | Promise | boolean | UrlTree {
    return Swal.fire({
      title: 'Are you sure?',
      text: 'You will be redirected to another page.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, redirect me!',
      cancelButtonText: 'No, stay here'
    }).then((result) => {
      if (result.isConfirmed) {
        return true; // 允许重定向
      } else {
        return false; // 取消重定向
      }
    });
  }
}

然后,在你的路由模块中使用这个路由守卫。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
import { ConfirmGuard } from './confirm.guard';

const routes: Routes = [
  { path: '', component: HomeComponent, canDeactivate: [ConfirmGuard] },
  { path: 'about', component: AboutComponent, canDeactivate: [ConfirmGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

现在,当用户在离开HomeComponentAboutComponent之前点击“确定”按钮时,将弹出一个确认对话框。如果用户确认重定向,就会进行重定向;如果用户取消,就会留在当前页面。

相关内容

热门资讯

透视透视!云扑克有透视吗(透视... 透视透视!云扑克有透视吗(透视)原来存在有挂(详细辅助玩家教程)1)辅助挂:进一步探索辅助透视大陆,...
总算了解!we-poker靠谱... 总算了解!we-poker靠谱吗,we-poker辅助器,2025新版(有挂攻略);支持2-10人实...
透视能赢!hhpoker底牌透... 透视能赢!hhpoker底牌透视脚本(透视)本来是真的有挂(详细辅助透明挂教程);1、超多福利:超高...
揭秘几款!哈糖大菠萝破解器,p... 1、揭秘几款!哈糖大菠萝破解器,pokermaster破解版,插件教程(有挂辅助);详细教程。2、哈...
透视中牌率!pokemmo辅助... 透视中牌率!pokemmo辅助器手机版下载(透视)本来是真的有挂(详细辅助AI教程)1、机器人多个强...
实操分享!拱趴大菠萝万能挂,w... 实操分享!拱趴大菠萝万能挂,wepoker插件程序激活码,实用技巧(有挂攻略)1、玩家可以在wepo...
透视智能ai!pokemmo辅... 透视智能ai!pokemmo辅助器脚本下载(透视)确实存在有挂(详细辅助新版2025教程)1、首先打...
一分钟快速了解!hhpoker... 自定义wepokerplus到底是挂了吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑...
透视新版!竞技联盟透视(透视)... 透视新版!竞技联盟透视(透视)一贯存在有挂(详细辅助曝光教程);1)辅助挂:进一步探索辅助透视大陆,...
终于知道!hhpoker免费辅... 终于知道!hhpoker免费辅助器,pokemmo手机版修改器,教你攻略(有挂辅助);最新版2024...