Using Alertify with canDeactivate

147 views Asked by At

I want to replace classic confirm with Alertify confirm in canDeactivate. I tried to implement the following codes but it does not return True when click on OK. Can anyone advise on this?

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;
}

}

2

There are 2 answers

0
Harun Yilmaz On

As confirm performs an async operation, you need to use an async solution such as Observable, Promise or async/await.

You can use Observable as follows:

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();
    });

}

Edit Note: Note that I added second callback for confirm to make sure to return false when user cancels confirmation.

0
JR Strayhorn On

I had to make some slight changes to get this working... but close to @Harun Yimaz's answer..

AlertifyService.ts

import * as alertify from 'alertifyjs';

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

in 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();
      }
    });

had to call observer.complete() after next for observable to complete correctly.