1

我想显示一个弹出窗口,警告用户如果他/她试图离开未保存更改的表单。我想使用 ngx-sweetalert2 组件,因为我的大多数应用程序都以类似的方式显示警报。但是,我在网上找不到任何解释这一点的文档或教程。即使 Stackoverflow 上有类似类型的请求(Angular 使用模式对话框在 canDeactivate Guard 服务中进行未提交的更改(表单脏)),它使用引导模式。也许有人可以帮助我从包含的链接中提供的解决方案中集成 ngx-sweetalert2 而不是 ngx-bootstrap。我真的很感激。

谢谢

@BizzyBob 谢谢你的回复。是的,我目前确实让警卫使用简单的确认对话框。请在提供的代码中查看我的实现:

// Guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

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

@Injectable({providedIn: 'root'})
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
    canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
        true :
        // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
        // when navigating away from your angular app, the browser will show a generic warning message
        // see http://stackoverflow.com/a/42207299/7307355
        confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
    }
}

// Component.ts

import { ComponentCanDeactivate } from '../../auth/guards/auth.guard';
import { Observable } from 'rxjs/Observable';
// @HostListener allows us to also guard against browser refresh, close, etc.
  @HostListener('window:beforeunload')
  canDeactivate(): Observable<boolean> | boolean {
    if (this.officeForm.dirty && this.officeForm.touched) {
      return false;
    } else {
      return true;
    }
  }
  
// Routing.ts
import { Routes } from '@angular/router';
import { OfficesComponent } from './offices.component';
import { RegionalOfficesComponent } from './regional-offices/regional-offices.component';
import { OfficeDetailsComponent } from './office-details/office-details.component';
import { OfficeEditComponent } from './office-edit/office-edit.component';
import { AuthGuard, PendingChangesGuard } from '../auth/guards/auth.guard';

export const OfficeRoutes: Routes = [
    { path: '', component: OfficesComponent },
    { path: 'add', component: OfficeEditComponent, canDeactivate: [PendingChangesGuard] },
    { path: ':regionCode', component: RegionalOfficesComponent },
    { path: ':regionCode/:id', component: OfficeDetailsComponent },
    { path: ':regionCode/edit/:id', component: OfficeEditComponent, canDeactivate: [PendingChangesGuard]}
];

4

0 回答 0