首页 > 解决方案 > 在 Map 之前按嵌套数组中的值排序

问题描述

使用 NG6 Rxjs 通过 http 返回一些数据。然后我将返回的数据分成两个 Observable。效果很好,但我需要先按嵌套数组中的值对数据进行排序。我可以在视图中触发事件后对数组进行排序,但在页面加载时不起作用。

此代码按外部数组中的值排序:

return this.http
  .get(this.apiUrl + 'PatchGroups/ForApp/' + appId)
  .pipe(
    map((data: Array<any>) => {
    return {
      ungrouped: data.filter(d => d.id < 0),
      grouped: data.filter(d => d.id > 0).sort((a, b) => a.name < b.name ? -1 : 1)
    };
    }),
   catchError(this.handleError)
  );

尝试按嵌套值排序,但效果不佳:

return this.http
  .get(this.apiUrl + 'PatchGroups/ForApp/' + appId)
  .pipe(
    map((data: Array<any>) => {
    return {
      ungrouped: data.sort((a, b) => a.server.name < b.server.name ? -1 : 1).filter(d => d.id < 0),
      grouped: data.filter(d => d.id > 0).sort((a, b) => a.name < b.name ? -1 : 1)
    };
    }),
   catchError(this.handleError)
  );

对每个 Observable 进行排序似乎很脏。我不能在传递给每个 Observable 之前对数据进行排序吗?

从我的组件:

this.appsApiService.getPatchGroups(appReconId)
  .subscribe(pg => {
    this.ungrouped_patchGroups = pg.ungrouped;
    this.grouped_patchGroups = pg.grouped;
  }
);

标签: angulartypescriptangular6rxjs6

解决方案


推荐阅读