首页 > 解决方案 > 如何结合两种方法来计算每个类别的项目?

问题描述

我有 Angular 8 应用程序。

我有两种方法可以显示每个类别有多少项目。来自后端的项目所以这是两个类别:

视图.html:

  <mat-tab>
          <ng-template mat-tab-label>
            <mat-icon class="goals">grade</mat-icon>
            <span i18n>Goals</span>{{ dossierItemsCountString(itemTypes.Goal) }}
            <a [routerLink]="['../', dossier.id, 'item', 'new', itemTypes.Goal]"
              ><mat-icon class="add_box">add</mat-icon>
            </a>
          </ng-template>
          <ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.Goal }"></ng-container>
        </mat-tab>
        <mat-tab>
          <ng-template mat-tab-label>
            <mat-icon class="action-steps">list</mat-icon>
            <span i18n>Action steps</span>{{ dossierItemsCountString(itemTypes.ActionStep) }}
            <a [routerLink]="['../', dossier.id, 'item', 'new', itemTypes.ActionStep]"
              ><mat-icon class="add_box">add</mat-icon>
            </a>
          </ng-template>
          <ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.ActionStep }"></ng-container>
        </mat-tab>


这是负责显示每个类别的项目的两个函数:


  dossierItemsCountBy(itemType: DossierItemTypeDto) {
    return this.typeSearchMatches[itemType.toString()] || { total: 0, matches: 0 };
  }

  dossierItemsCountString(itemType: DossierItemTypeDto) {
    const count = this.dossierItemsCountBy(itemType);

    if (this.hasSearchQuery) {
      return `(${count.matches}/${count.total})`;
    } else {
      return `(${count.total})`;
    }
  }

但我认为这两种方法可以用一种方法编写。或者也许你可以用它做一个管道?

所以我的问题是最好的方法是什么?以及如何做到这一点?

谢谢

标签: javascriptangulartypescriptrefactoring

解决方案


我不知道如何回答“什么是最好的方法?”这个问题。

无论如何,像这样修改 dossierItemsCountString() 应该可以工作:

const count = this.typeSearchMatches[itemType.toString()] || { total: 0, matches: 0 };

推荐阅读