Angular CanDeactivate无法正常工作

时间:2018-08-01 21:55:50

标签: angular typescript angular-routing

我正在尝试在路由中使用CanDeactivate函数,但是在另一条路由上调用canDeactivate函数时永远不会调用。

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

1 个答案:

答案 0 :(得分:3)

您需要将防护作为数组传递。 (您可以有多个。)

{ path: 'catalog', component: CatalogViewComponent, canDeactivate: [CanDeactivateGuard] }

并将防护添加为provider

providers: [CanDeactivateGuard],