0

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?

1 Answers1

0

Assuming that the register component path is 'register' you can do it in the following way

this.router.navigateByUrl('register');

Also You can use location.back() for navigation to the last page.

import {Component} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
 })
class LoginPage {

  constructor(private location: Location) 
  {}

  onBackClicked() {
    this.location.back();
  }
}
  • Thank you for answer, but in canDeactivate() method of canDeactevate guars it`s not work. I add console.log in code above: wirte 'before', 'after', but not navigated (with router.navigate or router.navigateByUrl) – Kontar Maryna May 10 '19 at 12:41
  • `const routes: Routes = [ ... { path: 'match', component: MatchValueCompatibilityComponent, canDeactivate: [CanDeactivateGuard] }... ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }` – Kontar Maryna May 13 '19 at 11:56