与异步一起使用时找不到管道'orderBy'错误



我正在尝试使用带有异步管道的 ngFor 中的 orderBy pipe。但它给出了以下错误:

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

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

<div *ngFor="let a of arr | async | orderBy: 'b'> </div>

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

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

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

与 AngularJS 不同,Angular 2+ 已经停止支持管道中的服务器构建。

必须定义自定义管道才能使用:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'yourPipeName'})
export class ExponentialStrengthPipe implements PipeTransform {
  // The pipe's transform method take first Argurment is the data using that 
  // pipe( which is data before the '|' mark in the template), the others 
  // parameter is optional
  // Your sort logic is in here
  transform(input: Array<any>, para1, para2) {
    return input.sort( (a,b) => a>b);
  }
}

然后,您应该在模块中声明新创建的管道,并且可以像这样在模板中使用它:

<div *ngFor="let a of arr | async | yourPipeName> </div>

最新更新