3

I'm implementing canDeactivate guard in my component using primeng confirmation service, creating an observable for user answer of the prompt. The problem is that when I try to navigate to sibling route and click yes to the prompt, the router does not redirect to the targeted page. If I'm using the simple confirm method it's working properly, but with Promise or Observable, it's not working and there are no errors. With other modules which are not siblings, it's working and redirects.

The guard is:

export interface CanComponentDeactivate {

canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

My implementation in the component:

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
return Observable.create((observer: Observer<boolean>) => {
  this.confirmService.confirm({
    accept: () => {
      observer.next(true);
      observer.complete();
    },
    reject: () => {
      observer.next(false);
      observer.complete();
    }
  });
 });
}

If I'm implementing it like this, is working.

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    return confirm('Are you sure to leave the page?');
  }

The version of Angular is 7.2.7

Petar Sabev
  • 66
  • 1
  • 7

0 Answers0