【问题标题】:How do you sort an Observable<Item[]> in Angular 6 with rxjs 6?如何使用 rxjs 6 对 Angular 6 中的 Observable<Item[]> 进行排序?
【发布时间】:2018-10-20 21:32:41
【问题描述】:

我只想对我的类类型“类别”的可观察数据进行排序。 So Observable 我要排序。

所以我用它升级到了 Angular6 和 rxjs6。我知道的一个可能很简单的 Typescript 问题是我如何进行“排序”操作,例如:

sort((x,y) => x.description < y.description ? -1 : 1)

在新的 Angular6 内部?我曾经在 5 年这样做过

var response = this.http.get<Category[]>(this.endpoint);
        .map((result: Response) => this.alphabetize(result));


alphabetize = (result: Response) => this.Categories = result.json()
.sort((x,y) => x.description < y.description ? -1 : 1)

而且效果很好。现在在 Angular 希望你使用的 HttpCLIENTModule 和 HttpClient 中更简单了:

var data = this.http.get<Category[]>(this.endpoint);

我只是把魔术 放在我的端点之前,它为我做了。凉爽的。但是我没有看到您如何轻松地进入对象内部以使用 Source、Pipe、from、of 对其进行排序。我知道这可能很简单,我只是不知道语法。

【问题讨论】:

    标签: typescript angular6 rxjs6


    【解决方案1】:

    对于 angular12,当我尝试这个解决方案时,它给了我这个错误。

    TypeError: Cannot read property ‘sort’ of undefined TypeError: Cannot read property ‘sort’ of undefined
    

    修复此错误。我用过管道

    import { Pipe, PipeTransform } from '@angular/core';
    
    
    @Pipe({
      name: 'sortByDate'
    })
    export class SortByDatePipe implements PipeTransform {
    
      transform(value: any, ...args: any[]): any {
        value = [...value]; // fixed to second error
    
        return value.sort((a, b) => new Date(b.date1).getTime() - new Date(a.date1).getTime());
    
      }
    
    }
    

    此时它给出了这个。

    TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ Error ?
    

    我已经在代码中解释了(上面),但是如果它不能解决错误,你可以检查here

    这里是html代码

    <div *ngFor="let item of data$ | async | sortByDate">
    //your code goes here
    </div>
    

    【讨论】:

      【解决方案2】:

      它是:

      this.http.get<Category[]>(this.endpoint).pipe(
        map(results => results.sort(...))
      );
      

      或者由于sort修改了现有数组,所以在do/tap中提供副作用在语义上更正确:

      this.http.get<Category[]>(this.endpoint).pipe(
        tap(results => {
          results.sort()
        })
      );
      

      【讨论】:

      • 在这种情况下它们应该类似地工作。但很高兴它奏效了。
      猜你喜欢
      • 2018-11-02
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多