CanDeactivate Guards.
Is it possible that when leaving a component, the canDeactivate not only renders a confirmation window with yes/no, but also navigates to another component? Something like this:
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
if (this.registrationService.isRegistered()) {
return true;
} else {
if (!confirm('If you do not register, your data will be lost. Click Cancel to go to Registration page.')) {
console.log('before');
this.router.navigate(['register']); // <----
console.log('after');
return false;
} else { return true; }
}
}
Now it's not work. When click Cancel just again and again open confirmation window and in cosole is: 'before', 'after'. Redirect to registration page only if first click to Cancel and than to Ok.
UPDATE: It`s seems i solved these with PROMISE
private isCanDeactivate: boolean;
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
if (this.registrationService.isRegistered()) {
return true;
} else {
if (!confirm('If you do not register, your data will be lost. Click Cancel to go to Registration page.')) {
console.log('press Cancel');
this.retrieve().then(() => this.afterPromise());
return this.isCanDeactivate;
} else {
console.log('press Ok');
return true; }
}
}
private retrieve(): Promise<any> {
return new Promise((resolve) => {
this.retrieveDataResolver = resolve;
this.setIsCanDeactivate();
});
}
private setIsCanDeactivate(): void {
this.isCanDeactivate = true;
this.retrieveDataResolver();
}
private afterPromise() {
this.router.navigate(['register']);
}
Can someone help with a better solution?