首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError: component.canDeactivate不是一个函数

TypeError: component.canDeactivate不是一个函数
EN

Stack Overflow用户
提问于 2018-12-20 14:09:59
回答 1查看 5.1K关注 0票数 8

当我构建我的CanDeactivateGuard时,我有这个错误。

TypeError: component.canDeactivate不是一个函数

我想使我的CanDeactivateGuard可重用,所以它应该是通用的。

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

然后,CanDeactivateGuard应该实现接口CanDeactivate。

我的守则:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

代码语言:javascript
复制
   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;
        }
    }

路线模块:

代码语言:javascript
复制
const routes: Routes = [
{
    path: '', component: TreeComponent, canDeactivate: [CanDeactivateGuard] , runGuardsAndResolvers: 'always',
}]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-20 15:44:16

TreeCanDeactivateGuard是什么?代码中的任何地方都没有引用它。

您不希望TreeCanDeactivateGuard扩展ComponentCanDeactivate,而是希望TreeComponent扩展ComponentCanDeactivate

让任何组件扩展ComponentCanDeactivate并实现canDeactivate,然后您就可以使用泛型保护CanDeactivateGuard了。

您还可以替换:

代码语言:javascript
复制
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.');

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53870294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档