簡體   English   中英

如何使函數與組件角度分開

[英]how to make a function separate from component angular

我在 2 個組件中有一個方法,它執行完全相同的邏輯。 我想要 DRY 代碼並制作一個執行此操作的函數。 如何在不為其提供服務的情況下將此方法作為單獨的功能?

private compareWithMainDevice(): void {
    this.newBuildingStatisticsService.getMainDeviceAggregates(this.isDetail).subscribe(mainDeviceAggregates => {
      this.mainDeviceId = mainDeviceAggregates.device_id;
      const mainDev = JSON.parse(JSON.stringify(mainDeviceAggregates));
      const other = this.deviceAggregates;
      this.deviceAggregates = [mainDev, ...other];
      const devs = this.deviceAggregates.reduce((a, b) => {
        b.cost.forEach(({ value, timestamp }, i) => {
          if (mainDev.cost.length > i && a.cost[i].value > b.cost[i].value) {
            return a.cost[i].value -= value;
          } else {
            return false;
          }
        });

        return a;
      });

      this.deviceAggregates = [...other, devs];
      this.setChartOption(true);
    });
  }

我不知道如何將組件的方法傳遞給這個函數。

我不確定我是否理解你的問題。

但是,在您的情況下,如果您想在兩個組件中共享compareWithMainDevice方法而無需重寫兩次,您可以使用具有此方法的抽象類以及您的共享類屬性(例如mainDeviceId )。 然后,每個組件都會擴展這個類,並且它們將可以訪問該方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM