对于未提交的更改,canDeactivate Guard服务中的Angular使用模式对话框(表单脏)

时间:2017-09-26 18:13:40

标签: angular typescript ngx-bootstrap confirm-dialog angular-guards

在我的Angular 4应用程序中,我有一些带有表单的组件,如下所示:

export class MyComponent implements OnInit, FormComponent {

  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({...});
  }

他们使用Guard服务来防止未提交的更改丢失,因此如果用户在请求确认之前尝试更改路由:

import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';

export interface FormComponent {
  form: FormGroup;
}

export class UnsavedChangesGuardService implements CanDeactivate<FormComponent> {
  canDeactivate(component: FormComponent) {
    if (component.form.dirty) {
      return confirm(
        'The form has not been submitted yet, do you really want to leave page?'
      );
    }

    return true;
  }
}

这是使用一个简单的confirm(...)对话框,它可以正常工作。

但是我想用更花哨的模态对话框替换这个简单的对话框,例如使用ngx-bootstrap Modal

如何使用模态来实现相同的结果呢?

8 个答案:

答案 0 :(得分:15)

我使用ngx-bootstrap ModalsRxJs Subjects解决了这个问题。

首先,我创建了一个模态组件:

import { Component } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BsModalRef } from 'ngx-bootstrap';

@Component({
  selector: 'app-confirm-leave',
  templateUrl: './confirm-leave.component.html',
  styleUrls: ['./confirm-leave.component.scss']
})
export class ConfirmLeaveComponent {

  subject: Subject<boolean>;

  constructor(public bsModalRef: BsModalRef) { }

  action(value: boolean) {
    this.bsModalRef.hide();
    this.subject.next(value);
    this.subject.complete();
  }
}

这是模板:

<div class="modal-header modal-block-primary">
  <button type="button" class="close" (click)="bsModalRef.hide()">
    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
  </button>
  <h4 class="modal-title">Are you sure?</h4>
</div>
<div class="modal-body clearfix">
  <div class="modal-icon">
    <i class="fa fa-question-circle"></i>
  </div>
  <div class="modal-text">
    <p>The form has not been submitted yet, do you really want to leave page?</p>
  </div>
</div>
<div class="modal-footer">
  <button class="btn btn-default" (click)="action(false)">No</button>
  <button class="btn btn-primary right" (click)="action(true)">Yes</button>
</div>

然后我使用主题修改我的后卫,现在它看起来像这样:

import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BsModalService } from 'ngx-bootstrap';

import { ConfirmLeaveComponent } from '.....';

export interface FormComponent {
  form: FormGroup;
}

@Injectable()
export class UnsavedChangesGuardService implements CanDeactivate<FormComponent> {

  constructor(private modalService: BsModalService) {}

  canDeactivate(component: FormComponent) {
    if (component.form.dirty) {
      const subject = new Subject<boolean>();

      const modal = this.modalService.show(ConfirmLeaveComponent, {'class': 'modal-dialog-primary'});
      modal.content.subject = subject;

      return subject.asObservable();
    }

    return true;
  }
}

在app.module.ts文件中转到@NgModule部分并将ConfirmLeaveComponent组件添加到entryComponents。

@NgModule({
  entryComponents: [
    ConfirmLeaveComponent,
  ]
})

答案 1 :(得分:2)

除了ShinDarth的优秀解决方案之外,似乎值得一提的是你也必须解雇模态,因为action()方法可能不会被触发(例如,如果你允许esc按钮或点击模态之外)。在这种情况下,observable永远不会完成,如果您使用它进行路由,您的应用可能会卡住。

我通过订阅bsModalService onHide属性并将其与行动主题合并来实现这一目标:

confirmModal(text?: string): Observable<boolean> {
    const subject = new Subject<boolean>();
    const modal = this.modalService.show(ConfirmLeaveModalComponent);
    modal.content.subject = subject;
    modal.content.text = text ? text : 'Are you sure?';
    const onHideObservable = this.modalService.onHide.map(() => false);
    return merge(
      subject.asObservable(),
      onHideObservable
    );
  }

在我的情况下,我将提到的onHide observable映射为false,因为在我的情况下解雇被视为中止( a&#39;是&#39;点击将产生一个我确认模式的积极结果。)

答案 2 :(得分:0)

这是我在使用ngx-bootstrap对话框离开某个路径之前获取确认对话框的实现。我有一个名为&#39; canNavigate&#39;的全局变量。在服务的帮助下。如果该变量为true或false,则该变量将保持布尔值,以查看是否可以导航。这个值最初是正确的,但如果我对我的组件进行更改,我会将其设为false,因此可以导航&#39;将是假的。如果为false,我将打开对话框,如果用户丢弃更改,它将通过获取queryParams进入所需的路径,否则它将不会路由。

@Injectable()
export class AddItemsAuthenticate implements CanDeactivate<AddUniformItemComponent> {

  bsModalRef: BsModalRef;
  constructor(private router: Router,
              private dataHelper: DataHelperService,
              private modalService: BsModalService) {
  }

  canDeactivate(component: AddUniformItemComponent,
                route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot,
                nextState?: RouterStateSnapshot): boolean {
    if (this.dataHelper.canNavigate === false ) {
      this.bsModalRef = this.modalService.show(ConfirmDialogComponent);
      this.bsModalRef.content.title = 'Discard Changes';
      this.bsModalRef.content.description = `You have unsaved changes. Do you want to leave this page and discard
                                            your changes or stay on this page?`;

      this.modalService.onHidden.subscribe(
        result => {
          try {
            if (this.bsModalRef && this.bsModalRef.content.confirmation) {
              this.dataHelper.canNavigate = true;
              this.dataHelper.reset();;
              const queryParams = nextState.root.queryParams;
              this.router.navigate([nextState.url.split('?')[0]],
                {
                  queryParams
                });
            }
          }catch (exception) {
            // console.log(exception);
          }
        }, error => console.log(error));
    }

    return this.dataHelper.canNavigate;

  }
}

答案 3 :(得分:0)

我通过Angular Material对话框实现了该解决方案:

在ngx-bootstrap模式中,材料的模态具有“ componentInstance”而不是“ content”:

if (component.isDirty()) {
  const subject = new Subject<boolean>();
  const modal = this.dialog.open(ConfirmationDialogComponent, {
    panelClass: 'my-panel', width: '400px', height: '400px',
  });

  modal.componentInstance.subject = subject;
  return subject.asObservable()
}
  return true;
}

答案 4 :(得分:0)

自从我与Ashwin来回交流以来,我决定发布我在Angular和Material中拥有的解决方案。

这是我的StackBlitz

这可行,但我想从“停用”页面添加异步响应的复杂性,就像我在应用程序中的使用方式一样。这是一个过程,请耐心等待。

答案 5 :(得分:0)

只需扩展mitschmidt提供的有关单击外部/退出按钮的附加信息,此canDeactivate方法就可以与Francesco Borzi的代码一起使用。我只是在函数中直接添加了对onHide()的订阅:

canDeactivate(component: FormComponent) {
        if (component.form.dirty) {
            const subject = new Subject<boolean>();

            const modal = this.modalService.show(ConfirmLeaveComponent, { 'class': 'modal-dialog-primary' });
            modal.content.subject = subject;

            this.modalService.onHide.subscribe(hide => {
                subject.next(false);
                return subject.asObservable();
            });

            return subject.asObservable();
        }

        return true;
    }

答案 6 :(得分:0)

您可以将值传递给对话框的afterClosed观察对象:

// modal.component.html
<mat-dialog-actions>
  <button mat-button mat-dialog-close>Cancel</button>
  <button mat-button [mat-dialog-close]="true">Leave</button>
</mat-dialog-actions>
// unsaved-changes.service.ts
@Injectable({ providedIn: 'root' })
export class UnsavedChangesGuardService
  implements CanDeactivate<FormComponent> {
  constructor(private _dialog: MatDialog) {}

  canDeactivate(component: FormComponent) {
    if (component.form.dirty) {
      const dialogRef = this._dialog.open(UnsavedChangesDialogComponent);
      return dialogRef.afterClosed();
    }

    return true;
  }
}

答案 7 :(得分:0)

这是一个没有主题的工作解决方案,您可以添加一个布尔属性已确认来区分用户是点击了取消还是确认

import { Component, OnInit } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-leave-form-confirmation',
  templateUrl: './leave-form-confirmation.component.html',
  styleUrls: ['./leave-form-confirmation.component.scss']
})
export class LeaveFormConfirmationComponent implements OnInit {
  confirmed = false;
  constructor(public bsModalRef: BsModalRef) { }

  ngOnInit(): void {
  }
  confirm = () => {
    this.confirmed= true;
    this.bsModalRef.hide()
  }
}

这里是 html

<div class="modal-header">
  <h4 class="modal-title pull-left">Confirmation</h4>
</div>
<div class="modal-body">
  <h2>Data will be lost, Are you sure to leave the form?</h2>
</div>-*
<div class="modal-footer">
  <button type="button" class="btn btn-default" (click)="confirm()">confirm</button>
  <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">cancel</button>
</div>

这是你的 canDeactivate 方法

 canDeactivate(
    component: DataStatus,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if(!component.isDataSaved()) {
      const modalRef = this.modalService.show(LeaveFormConfirmationComponent,  {
        backdrop: false,
        ignoreBackdropClick: true
      })
      return modalRef.onHidden.pipe(map(_ => modalRef.content.confirmed));
    }
    return of(true);
  }