我正在尝试在路由中使用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
最佳答案
您需要将防护作为数组传递。 (您可以有多个。)
{ path: 'catalog', component: CatalogViewComponent, canDeactivate: [CanDeactivateGuard] }
并添加防护罩作为
provider
:providers: [CanDeactivateGuard],
关于angular - Angular CanDeactivate无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51642802/