Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular CanDeactivate isn't working

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

like image 228
Koushik Ravulapelli Avatar asked Aug 01 '18 21:08

Koushik Ravulapelli


1 Answers

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],
like image 198
Kim Kern Avatar answered Sep 24 '22 00:09

Kim Kern