Angular 2/4 prevent user to leave component if changes not saved
Asked Answered
T

3

7

I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

Can someone tell me what am i doing wrong?

Tachymetry answered 4/12, 2017 at 19:43 Comment(1)
@MilanRaval Yes, i implemented ComponentCanDeactivate and rewrite the function canDeactive(): boolean. (You can see the code in the middle of my post). It only returns if form is dirty or notTachymetry
T
9

The issue was caused by lazy loading

Instead of having this in your app routing:

path: 'dashboard',
        canDeactivate: [PendingChangesGuard], <-- causing issue
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

You need to remove the canDeactive from the app routing and move it to the module routing.

const routes: Routes = [
  {
    path: '',
    component: DashboardComponent,
    canDeactivate: [ PendingChangesGuard ]
  }
Tachymetry answered 6/12, 2017 at 17:56 Comment(1)
Thank you! That's what I was missing!Polyzoic
F
0

In your PendingChangesGuard, try to inject the component itself, not the interface:

export class PendingChangesGuard implements CanDeactivate<DashboardComponent> {
  constructor() {}
  canDeactivate(component: DashboardComponent): boolean {
  ...
  }

You cannot inject an interface using Angular DI as interfaces are just Typescript constructs and do not exist in Javascript code produced with the compilation process.

For more information, have a look at this SO question.

Franckot answered 4/12, 2017 at 20:27 Comment(4)
Thanks for replying, I tried it and i got the same error which is: TypeError: Cannot read property 'canDeactivate' of nullTachymetry
I think that you need to declare a component in your routing setup for guards to work. Something like: path: 'dashboard', canDeactivate: [PendingChangesGuard], component: DashboardComponent What you could do is setup your guard 'lower' in the dashboard module routing configuration i suppose. Let me know if it works.Franckot
This is what i have in my routing: path: 'dashboard', canDeactivate: [PendingChangesGuard], loadChildren: './views/dashboard/dashboard.module#DashboardModule' }Tachymetry
Yes, i see that from the question. From my understanding, you cannot add a route guard that depend on some component logic without specifying a component in the route configuration and that is why you always get an exception.Franckot
A
0

I implement like this

Deactive-guard-service.ts

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class DeactivateGuardService implements  CanDeactivate<CanComponentDeactivate>{

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

Component.ts

checkSave(): Promise<boolean> {
    var prom = new Promise<boolean>((resolve, reject) => {
      //check saved change
        if(saved) resolve(true);
        else reject(false);
    });
    return prom;
  }

  canDeactivate(): Promise<boolean> {

    return this.checkSave().catch(function () {
      return false;
    });
  }
Apiarian answered 5/12, 2017 at 2:41 Comment(3)
I tried implementing like you did, it gave me the same error. It tells me that : TypeError: Cannot read property 'canDeactivate' of nullTachymetry
I think your issue cause u are using lazy load module . You can refer to this topic github.com/angular/angular/issues/16868 Try put CanDeactive into main route of DashboardModuleApiarian
Thanks @Apiarian that was the issue!Tachymetry

© 2022 - 2024 — McMap. All rights reserved.