I'm trying to use the CanDeactivate
function in the routing but canDeactivate
function is never called when invoked on another route.
CanDeactivateGuard :
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 CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
CatalogViewComponent :
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from "rxjs";
import {CanComponentDeactivate} from '../../can-deactivate.guard';
@Component({
selector: 'home',
template: `
<h1>Catalog</h1>
`,
})
export class CatalogViewComponent implements CanComponentDeactivate{
canDeactivate(): Observable<boolean> | boolean {
console.log('working'); // Not Entering this function when invoked another route
return false;
}
}
routing.module.ts :
{ path: 'catalog', component: CatalogViewComponent, canDeactivate: CanDeactivateGuard },
Stackblitz Link
You need to pass the guard as an array. (You could have more than one.)
{ path: 'catalog', component: CatalogViewComponent, canDeactivate: [CanDeactivateGuard] }
and also add the guard as a provider
:
providers: [CanDeactivateGuard],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With