componentcandeactivate

componentcandeactivate

我在建立CandeActivateGuard时有这个错误。
uncaught(在promise中):typeerror:component.candeActivate不是函数
我想让我的CandeActivateGuard可重用,所以它应该是通用的。
因此,我构建了一个抽象类componentcandeactivate,然后在treecandactivateguard中扩展它。
然后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;
    }
}

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

路由模块:
const routes: Routes = [
{
    path: '', component: TreeComponent, canDeactivate: [CanDeactivateGuard] , runGuardsAndResolvers: 'always',
}]

最佳答案

什么是TreeCanDeactivateGuard?它在代码中的任何地方都没有被引用。
您不希望TreeCanDeactivateGuard扩展ComponentCanDeactivate,而是希望TreeComponent扩展ComponentCanDeactivate
使任何组件扩展ComponentCanDeactivate并实现canDeactivate,然后您就可以使用通用的guardCanDeactivateGuard
您还可以替换:

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

08-08 03:23