未捕获(承诺):TypeError:component.canDeactivate不是函数

时间:2018-12-20 14:09:59

标签: angular typescript

构建 CanDeactivateGuard 时出现此错误。

  

未捕获(承诺):TypeError:component.canDeactivate不是函数

我想让我的 CanDeactivateGuard 可重用,所以应该通用。

因此,我构建了一个名为 ComponentCanDeactivate 的抽象类,然后在 TreeCanDeactivateGuard 中对其进行了扩展。

然后, CanDeactivateGuard 应该实现接口 CanDeactivate

我的代码:

apply

}

TreeCanDeactivateGuard

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;
    }
}

}

CanDeactivateGuard

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;
      }
}

路由模块:

   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;
        }
    }

2 个答案:

答案 0 :(得分:0)

您不能直接通过抽象类调用absctact方法。不得不通过孩子上课。喜欢

     canDeactivate(component: TreeCanDeactivateGuard): boolean {

        if (!component.canDeactivate()) {

答案 1 :(得分:0)

什么是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.');