【问题标题】:How to perform groupBy operation in Angular 2?如何在 Angular 2 中执行 groupBy 操作?
【发布时间】:2015-10-15 21:48:42
【问题描述】:

Angular 2:2.0.0-alpha.31 / Typescript 1.5

我从 http.get 查询请求数据

this.http.get('/data/players.json')
                  .toRx()
                  .map((res) => res.json())
                  .subscribe((data) => {
                        this.players = data;
                  });

这个查询返回这个 Json 对象 (this.players)

[
  {"team":"teamA","name":"player1","age":"1"},
  {"team":"teamA","name":"player2","age":"1"},
  {"team":"teamA","name":"player3","age":"1"},
  {"team":"teamB","name":"player4","age":"1"},
  {"team":"teamB","name":"player5","age":"1"}
]

然后我想显示按球队分组的球员

teamA: player1,player2,player3
teamB: player4,player5

我如何在 Angular2groupBy team(直接进入@View?)?

更新

我在 Angular 1 上看到,这可以在视图中使用 ngFor 上的| groupBy:'propertyName' 来完成。 Angular 2 上有类似的东西吗?

【问题讨论】:

    标签: javascript angular typescript group-by


    【解决方案1】:

    你可以使用过滤器吗?

    var test = [
      {"team":"teamA","name":"player1","age":"1"},
      {"team":"teamA","name":"player2","age":"1"},
      {"team":"teamA","name":"player3","age":"1"},
      {"team":"teamB","name":"player4","age":"1"},
      {"team":"teamB","name":"player5","age":"1"}
    ];
    
    function FilterByTeam(obj){
        console.log(obj);
        return obj.team === "teamA";
     }
    
     var teamA = test.filter(FilterByTeam);
     console.log(teamA)
    

    【讨论】:

    • 不幸的是,我想动态地将其放入视图中。我在 angular1 上看到了,这可以通过:player in players | groupBy: 'team' 来完成,我正在寻找类似的东西。谢谢
    【解决方案2】:

    不确定它引入了哪个版本的 Angular2,但您可以致电 RX's GroupBy function。我认为您也不需要在较新的版本中调用.toRx()

    在订阅之前添加如下内容:

    .map((res) => res.json())
    .groupBy(
        x => x.team,
        x => x
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2022-10-06
      • 2016-11-10
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 2017-05-16
      • 2016-09-04
      相关资源
      最近更新 更多