0

我想用 canDeactivate 中的 Alertify 确认替换经典确认。我尝试实现以下代码,但单击“确定”时它不返回 True。有人可以就此提出建议吗?

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SignupComponent } from 'src/app/signup/signup.component';
import { AlertifyService } from 'src/app/_helpers/alertify.service';

@Injectable()
export class SignUpPUS implements CanDeactivate <SignupComponent> {

constructor(private alertifyService: AlertifyService) {}

canDeactivate(component: SignupComponent) {
    if (component.signUpForm.dirty) {

         this.alertifyService.confirm('Leave Page', 'Are you sure you want to continue? Any unsaved changes will be lost', () => {
            return true;
        });

    }
    return false;
}

}

4

2 回答 2

1

confirm执行异步操作时,您需要使用异步解决方案,例如Observable,Promiseasync/await.

您可以Observable按如下方式使用:

canDeactivate(component: SignupComponent) {
    return new Observable((observer) => {

        if (component.signUpForm.dirty) {

             this.alertifyService.confirm('Leave Page', 'Are you sure you want to continue? Any unsaved changes will be lost', 
               () => {
                 observer.next(true);
               },
               () => {
                 observer.next(false);
               }
             );
        }else{
           observer.next(false);
        }

        observer.complete();
    });

}

编辑注意:请注意,我添加了第二个回调,confirm以确保在用户取消确认时返回 false。

于 2019-03-18T07:32:11.547 回答
0

我必须做一些细微的改变才能让它工作......但接近@Harun Yimaz的回答......

警报服务.ts

import * as alertify from 'alertifyjs';

  confirmCancel(
    message: string,
    okCallback: () => any,
    cancelCallback: () => any
  ) {
    alertify.confirm(message, okCallback, cancelCallback);
  }

在guard.ts中

constructor(private alertify: AlertifyService) {}

canDeactivate(component: MemberEditComponent) {
    return new Observable<boolean>(observer => {
      if (component.editForm.dirty) {
        this.alertify.confirmCancel(
          'Are you sure you want to continue? Any unsaved changes will be lost',
          () => {
            observer.next(true);
            observer.complete();
          },
          () => {
            observer.next(false);
            observer.complete();
          }
        );
      } else {
        observer.next(true);
        observer.complete();
      }
    });

必须在 next 之后调用observer.complete() 才能正确完成observable。

于 2020-02-24T14:03:14.493 回答