【问题标题】:The pipe 'orderBy' could not be found error coming when using with async使用异步时找不到管道“orderBy”错误
【发布时间】:2019-11-23 00:36:57
【问题描述】:

我正在尝试将 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

arr 返回 observables,没有 orderBy 可以正常工作,但是当我想使用 orderBy 时,它会报错:

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

【问题讨论】:

  • Angular 没有任何名为 orderBy 的管道(强烈建议不要创建一个)。你定义了一个吗?为什么你认为这应该有效?您是否将 Angular 与 AngularJS 混淆了?这是两个不同的框架。
  • @JBNizet 我们可以使用异步管道吗?
  • 是的,你可以。定义不能使用的管道有什么意义?这是您可以在其中查找有关 Angular 的文档的页面。请做。 angular.io
  • @JBNizet 您能否帮助我在异步管道之后发送数据并对结果进行排序,以便我可以按自定义顺序显示它们。除了创建自定义管道之外还有其他方法吗?

标签: angular typescript rxjs angular6 observable


【解决方案1】:

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

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

这保证了排序只在真正需要发生时发生,IE,当数组改变时。然后你就不需要使用任何管道了,你可以将你的排序操作保存在真正属于它们的代码中。

【讨论】:

  • @bryn60 您是否建议订阅组件内的可观察对象而不是使用异步管道?
  • 不,继续使用异步管道。但只需在链中添加一个 map 运算符来为您进行排序,而不是依赖于排序管道。
  • return observable .pipe(map(documents => _.sortBy(documents, (document) => document.startDate)));
  • 虽然控制台中没有错误,但上面的代码并未对数据进行排序。我在这里做错了吗?
  • SortBy of underscore 在 subscribe 方法中工作。
【解决方案2】:

不像 AngularJS,Angular 2+ 有 stopped support serveral build in pipe。

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

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>

【讨论】:

  • 我们可以使用异步管道结果到这个自定义管道吗,它是否将数据数组或可观察对象数组发送到自定义管道。
  • 是的,它像普通管道一样工作,可以在数据后面有一个或多个管道
猜你喜欢
  • 2017-01-30
  • 2021-05-22
  • 2021-02-02
  • 1970-01-01
  • 2020-08-29
  • 2023-03-29
  • 2019-04-12
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多