Angular6:使用 Lodash 的记忆功能会出错

Angular6: Memoizing function with Lodash gives error

预期行为:

我有一个管道,它接受一个对象和一个类型,它 return 是该对象的一个​​变量,具体取决于哪种类型。我想记住这个函数,因为它应该总是 return 具有相同参数的相同值。管道应该 return 一系列链接实体的字符串。

观察到的行为:

抛出一个错误,显示 this.getDefaultEntityTypeForLinkedEntities is not a function。我在memoized的方法中使用了这个方法

代码:

export class LinkCountPipe implements PipeTransform {

  public transform(linkCount: LinkCount, type: EntityType, via: EntityType): string {
    const memoGetLinkCount = _.memoize(this.getLinkCount);
    const result = memoGetLinkCount(linkCount, type, via);
    return result ? result.toString() : undefined;
  }

  public getLinkCount(linkCount: LinkCount, type: EntityType, via: EntityType): number {
    const someType = via ? via : this.getDefaultEntityTypeForLinkedEntities(type);
    switch (someType) {
      case EntityType.APPLICATION:
        return linkCount.nbApplications;
      case EntityType.ENTITLEMENT:
        return linkCount.nbEntitlements;
      case EntityType.PERMISSION:
        return linkCount.nbPermissions;
      case EntityType.ROLE:
        return linkCount.nbRoles;
      case EntityType.USER:
        return linkCount.nbUsers;
    }
  }

  public getDefaultEntityTypeForLinkedEntities(type: EntityType) {
    return DatatableSettings.getDefaultEntityTypeForLinkedEntities(type);
  }
}

澄清:

我在应用程序中使用实体。每个实体都链接到其他类型的实体(我有用户、角色、权限……)。每个实体对象都包含一个从服务器获取的 linkCount 对象,它包含例如用户的链接角色、权利和应用程序。在我的 HTML 中,我使用:element.linkCount | linkcount: type : via。 linkcount 纯管道用于获得更好的性能。它应该做的是:它获取实体的 linkCount 对象,它传递实体的类型(例如用户)和一个 via(这是可选的,它用于显示数据表中的其他内容而不是默认链接实体。例如:用户数据表并显示链接权限而不是角色)。根据类型,它只是 returns linkCount 对象的正确变量。

我认为您在这里遇到 this 问题以及 memoize 的概念问题,即当它仅使用第一个时您将 3 个参数传递给它一个默认组成 map cache key.

this 问题来自这样一个事实,即默认情况下 momoize 是通过记忆函数 .

this 绑定调用的

See the _.memoize documentation

By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with the this binding of the memoized function.