【问题标题】:Sum of groupBy elements using PipeTransform使用 PipeTransform 的 groupBy 元素的总和
【发布时间】:2020-04-23 05:30:48
【问题描述】:

我在 Angular 项目和后端做了一个 groupBy,使用 ASP.NET Web Api 检索 groupBy 功能的数据。我使用此链接使其工作 - Angular groupBy 使用 PipeTransform 接口进行实施。它工作正常,当前输出如下:

Jack
ID   - Date       - Points
1001 - 04/01/2020 - 10
1001 - 05/01/2020 - 10

John
ID   - Date       - Points
1002 - 04/01/2020 - 10
1002 - 05/01/2020 - 20

所以下面是数据结构:

data = [
{ "id": "1001", "name": "Jack", "date": "2020-01 - 05T00: 00: 00", "points": 10 },
{ "id": "1001", "name": "Jack", "date": "2020-01 - 04T00: 00: 00", "points": 10 },
{ "id": "1002", "name": "John", "date": "2020-01 - 05T00: 00: 00", "points": 20 },
{ "id": "1002", "name": "John", "date": "2020-01 - 04T00: 00: 00", "points": 10 }     
];

在前端,我这样做是为了渲染视图:

<div class="col-xs-12 table-responsive">
    <table *ngIf="data" class="table table-responsive" border="0">
      <tbody *ngFor="let details of data | groupBy: 'name'">
        <tr>
          <th colspan="2">
             <h2>{{details.key}}</h2> <!--Here name is shown-->
          </th>
        </tr>
        <tr>
          <th>Sl No.</th>
          <th>Id</th>
          <th>Name</th>
          <th>Date</th>
          <th>Points</th>
        </tr>

        <tr *ngFor="let value of details.value; let i = index">
          <td>{{i + 1}}</td>
          <td>{{value.id}}</td>
          <td>{{value.name}}</td>
          <td>{{value.date | date :'dd-MMM-yyyy'}}</td>
          <td>{{value.points}}</td>
        </tr>
        <tr>Total Points: {{sum}}</tr> <!--Expecting total points for groupBy-->
      </tbody>
    </table>
</div>

我的预期输出如下:

Jack
ID   - Date       - Points
1001 - 04/01/2020 - 10
1001 - 05/01/2020 - 10
______________________________
Total Points: 20

John
ID   - Date       - Points
1002 - 04/01/2020 - 10
1002 - 05/01/2020 - 20
______________________________
Total Points: 30

我是 stackblitz 的新手,无法构建要渲染的项目。这是我尝试使用代码的链接 - Angular groupBy with stackblitz

注意:我尝试像这样在TypeScript 文件中求和,但这会计算总点数,而不是groupBy

public sum: number = 0;

GetUserPoints() {
  debugger;

  for (let i = 0; i <= this.data.length; i++) {
     this.sum += this.data[i].points;
     console.log(this.data.length);
  }
}

【问题讨论】:

  • 究竟缺少什么或不起作用?总和的计算?
  • 你查看开发工具控制台是否有错误?
  • 实际上没有错误。我想得到@Batajus 的总和。

标签: asp.net angular asp.net-web-api


【解决方案1】:

如果你想通过使用管道来保持这种动态和可重用,你可以通过创建 PluckPipeSumPipe 来计算点的总和,就像我在这个 stackblitz 中所做的那样 然后在你的模板中使用&lt;tr&gt;Total Points: {{details.value | pluck:'points' | sum}}&lt;/tr&gt; 例如:https://stackblitz.com/edit/angular-iurvtc

顺便说一句:你的 stackblitz 没有渲染,因为时间戳中有空格。

【讨论】:

  • 我尝试运行您使用stackblitz 链接提供的项目,但不幸的是,视图没有呈现@A.Winnen。我错过了什么吗?非常感谢您的时间和精力。
  • 你确定吗?它为我工作。错误请查看浏览器控制台
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 2019-03-23
  • 2022-01-17
  • 2021-07-06
  • 2012-11-07
  • 2022-10-18
  • 1970-01-01
相关资源
最近更新 更多