【问题标题】:GroupBy 'rxjs/operators' to array with key and array of values in angular 6GroupBy 'rxjs/operators' 以 Angular 6 的键和值数组排列
【发布时间】:2026-01-16 17:25:02
【问题描述】:

我有一个问题,我从 web api 得到一个数组作为响应

响应结构很简单:

interface CabinInfo {
    id: number;

    projectId: number;
    cabinId: number;
    ipAddress: string;
    port: number;
}

所以现在我需要按 projectId 对其进行分组,所以很自然地我会使用 rxjs/operators 来获取一些我可以在 html 中迭代的排序 od 数组,所以我正在使用:

        this.clientService.GetAllApplications()
            .subscribe(result => {
                const projectsObservable: Observable<CabinInfo> = from(result);
                const projectsList = projectsObservable.pipe(groupBy(cabin => cabin.projectId, cabin => cabin)
                    , mergeMap(group => group.pipe(map(() => ({ projectId: group.key, cabins: group.pipe(toArray())})))));

            }, error => { console.error(error); });

但它不能按我的意愿工作,我希望像

Array<number|CabinInfo[]> 

我得到了一些复杂的东西,比如

Observable<{projectId: number, Observable<CabinInfo>[]}> 

有没有办法把它转换成简单的数组??

【问题讨论】:

    标签: angular typescript grouping


    【解决方案1】:

    so naturally i would use rxjs/operators

    我的朋友,你生活在一种奇怪的天性中……

    使用Array.prototype.reduce函数:

    .subscribe(result => {
      this.groupedResults = result.reduce((p, n) => {
        if (!p[n.projectId]) { p[n.projectId] = []; }
        p[n.projectId].push(n);
        return p;
      }, {});
    });
    

    【讨论】:

      【解决方案2】:

      由于您使用的是 angular,因此您可以在 html 中使用异步管道,因此您无需订阅 observable,但您可以让 angular 处理该逻辑。相反,您可以将操作符放入您的 observable。

      this.$applications = this.clientService.GetAllApplications()
              .pipe(
                  groupBy(cabin => cabin.id),
                  mergeMap(group => group.pipe(toArray()))
              );
      

      在您的 html 中,您将拥有如下内容:

      <div *ngFor="let c of $applications | async">
      
      </div>
      

      【讨论】:

        最近更新 更多