与异步使用时出现管道“orderBy”无法找到错误

Sre*_*ddy 0 observable rxjs typescript angular angular6

我正在尝试将 ngFor 中的 orderBy 管道与异步管道一起使用。但它给出以下错误:

ERROR Error: Uncaught (in promise): Error: Template parse errors:
The pipe 'orderBy' could not be found ("
          </div>
          <div
            *ngFor="let a of arr | async | orderBy: 'b': ng:///TestModule/TestComponent.html@95:34
Error: Template parse errors:
The pipe 'orderBy' could not be found ("
          </div>
          <div
Run Code Online (Sandbox Code Playgroud)

arr 返回 observables,它在没有 orderBy 的情况下工作正常,但是当我想使用 orderBy 时它给出错误:

<div *ngFor="let a of arr | async | orderBy: 'b'> </div>
Run Code Online (Sandbox Code Playgroud)

bry*_*n60 5

我建议您不要通过自定义管道进行排序。Angular 取消 orderBy 管道是有原因的,因为它的执行效率通常很低。无论如何,您正在使用可观察流,那么为什么不像这样将排序添加为组件中的运算符呢?

this.arr = this.arr.pipe(map(arr => arr.sort((a,b) => a > b))); // really any sort logic you want
Run Code Online (Sandbox Code Playgroud)

这保证了排序仅在真正需要发生时发生,即当数组更改时。然后,您不需要使用任何管道,并且可以将排序操作保留在它们真正所属的代码中。