当我构建我的CanDeactivateGuard时,我有这个错误。
TypeError: component.canDeactivate不是一个函数
我想使我的CanDeactivateGuard可重用,所以它应该是通用的。
为此,我构建了一个名为ComponentCanDeactivate的抽象类,然后在TreeCanDeactivateGuard中对其进行了扩展。
然后,CanDeactivateGuard应该实现接口CanDeactivate。
我的守则:
import { HostListener } from '@angular/core';
export abstract class ComponentCanDeactivate {
public abstract canDeactivate(): boolean;
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = true;
}
}}
TreeCanDeactivateGuard:
import { ComponentCanDeactivate } from './canDeactivate/component-can-deactivate';
import { NodeService } from '../tree/node.service';
export abstract class TreeCanDeactivateGuard extends ComponentCanDeactivate {
constructor(private _nodeService: NodeService) {
super();
}
public canDeactivate(): boolean {
if (this._nodeService.treeChangesTracer === false) {
return true;
} else {
return false;
}
}}
The CanDeactivateGuard
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ComponentCanDeactivate } from './component-can-deactivate';
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<ComponentCanDeactivate> {
constructor() { }
canDeactivate(component: ComponentCanDeactivate): boolean {
if (!component.canDeactivate()) {
if (confirm('You have unsaved changes! If you leave, your changes will be lost.')) {
return true;
} else {
return false;
}
}
return true;
}
}路线模块:
const routes: Routes = [
{
path: '', component: TreeComponent, canDeactivate: [CanDeactivateGuard] , runGuardsAndResolvers: 'always',
}]发布于 2018-12-20 15:44:16
TreeCanDeactivateGuard是什么?代码中的任何地方都没有引用它。
您不希望TreeCanDeactivateGuard扩展ComponentCanDeactivate,而是希望TreeComponent扩展ComponentCanDeactivate。
让任何组件扩展ComponentCanDeactivate并实现canDeactivate,然后您就可以使用泛型保护CanDeactivateGuard了。
您还可以替换:
if (confirm('You have unsaved changes! If you leave, your changes will be lost.')) {
return true;
} else {
return false;
}与:return confirm('You have unsaved changes! If you leave, your changes will be lost.');
https://stackoverflow.com/questions/53870294
复制相似问题