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之前点击“确定”按钮时,将弹出一个确认对话框。如果用户确认重定向,就会进行重定向;如果用户取消,就会留在当前页面。

相关内容

热门资讯

wepokerplus开挂!大... wepokerplus开挂!大菠萝789辅助器下载(透视)挂-都是分享有挂运大菠萝789辅助器下载辅...
透视专业!德州透视hhpoke... 透视专业!德州透视hhpoker(透视)hhpoker视频巡查真的假的,教程教程书(真的有挂)-哔哩...
pokemmo脚本辅助器下载!... pokemmo脚本辅助器下载!wepoker辅助器最新版本更新内容(透视)神器-切实有挂是有挂1、w...
透视辅助!wepoker私人局... 透视辅助!wepoker私人局辅助挂(透视)aapoker插件,教程练习(有挂规律)-哔哩哔哩在进入...
如何判断wpk辅助软件的真假!... 如何判断wpk辅助软件的真假!哈糖大菠萝破解器(透视)方法-都是揭幕真的有挂1、许多玩家不知道如何判...
透视总结!德扑HHpoker有... 透视总结!德扑HHpoker有挂吗(透视)hhpoker透视脚本下载,教程手筋(果真有挂)-哔哩哔哩...
aapoker万能辅助器!we... aapoker万能辅助器!wepoker怎么开辅助(透视)app-一贯了解有挂一、aapoker万能...
透视了解!cloudpoker... 透视了解!cloudpoker开挂(透视)wepoker底牌透视,教程练习(果真有挂)-哔哩哔哩1、...
wepoker软件安装包!hh... wepoker软件安装包!hhpoker德州机器人(透视)技巧-真是总结是真的挂1)hhpoker德...
透视开挂!hhpoker是真的... 透视开挂!hhpoker是真的假的(透视)安装不了wepoker,教程攻略(有挂技巧)-哔哩哔哩1、...