angular2: CanDeactivate guard

跟風遠走 提交于 2019-12-02 23:06:29

i have found this solution, instead of creating a candeactivate guard for every component, you will create one guard service and add a candeactivate method to every component you want to add this option, so first you have to add this service file "deactivate-guard.service.ts":

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

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

then you have to provide in the app module:

providers: [
    DeactivateGuardService
  ]

now in the component you want to protect, add the function:

export class ExampleComponent {
    loading: boolean = false;
    //some behaviour that change the loading value
    canDeactivate() {
        console.log('i am navigating away');
        if (this.loading) {
            console.log('no, you wont navigate anywhere');
            return false;
        }
        console.log('you are going away, goodby');
        return true;
    }
}

you can see that the variable loading is local to the component. the final step is to add the directive to the component in the routing module:

{ 
  path: 'example', 
  canDeactivate: [DeactivateGuardService],
  component: ExampleComponent 
}

and thats it, i hope this was helpfull, goodluck.

Damn, bug...Note to self: next time, check the issues board first

https://github.com/angular/angular/issues/12851#event-880719778

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!