JHipster/Angular:已删除的 pureFilter 管道的替代方案(在 JHipster 7.0.0.-beta.0 中)

JHipster/Angular: Alternative for pureFilter pipe which was removed (in JHipster 7.0.0.-beta.0)

我还在通过使用 JHipster 6.5.0 的《Full Stack Development with JHipster (Second Edition)》一书学习 JHipster。

在第 5 章“定制和进一步开发”中,应添加过滤器功能(第 135 页)。作者使用

a pipe provided by JHipster to filter the list using the name field of the product.

*ngFor="let product of (products | pureFilter:filter:'name'); trackBy: trackId">

使用 JHipster 7.0.0。我收到一条错误消息,告诉我“pureFilter”是一个未知管道。

我研究了一下发现pureFilter管道好像是在ng-jhipster/pipe/pure-filter.pipe.d.ts中定义的。

但是当“ng-jhipster”包与“generator-jhipster”合并时(JHipster 7.0.0.beta 发行说明:https://www.jhipster.tech/2020/12/21/jhipster-release-7.0.0-beta.0.htmlpure-filter.pipe 已被 kaidohallik(GitHub 问题 #12909:https://github.com/jhipster/generator-jhipster/issues/12909)删除,他说在“ [angular]改进日志视图”(#12924)。

如何在没有 pureFilter 命令的情况下实现所需的过滤?

非常感谢您的支持。

正如我在评论中提到的,像 order by 和 filter 这样的纯管道表现不佳,因此它们已被删除。你可以使用 observables 来过滤你的数组,它们工作得很好。

这里有一个示例,包括 http。将代码应用于您的用例。我在这里使用 shareReplay 不触发每次搜索的 http 请求。 shareReplay 可能并非在所有情况下都适用,例如,如果列表经常更新,但此处未考虑。

示例中提供了一个供用户搜索的搜索字段,它附加到表单控件,我们会在表单控件发生变化时进行监听,然后执行过滤,name 属性,正如您在样本中所拥有的:

import { FormControl } from '@angular/forms';

import {
 debounceTime,
 map,
 shareReplay,
 startWith,
 switchMap
} from 'rxjs/operators';

interface Product {
  name: string;
}

// ......

searchCtrl = new FormControl();

products$ = this.searchCtrl.valueChanges.pipe(
  startWith(''), // trigger initially
  debounceTime(200), // just a slight debounce if user types fast
  switchMap(val => { // get the data from the service and filter
    return this.service.products$.pipe(
      map((products: Product[]) =>
        products.filter((product: Product) => {
          return product.name.toLowerCase().includes(val.toLowerCase());
        })
      )
    );
  })
);

服务变量将如下所示:

products$ = this.http
  .get<Product[]>('https://jsonplaceholder.typicode.com/users')
  .pipe(shareReplay());

如果您不使用 http,请记住为您的数组创建一个可观察对象,您可以使用 of(put your array here).

在模板中,我们使用 async 管道订阅可观察组件 products$:

<ul>
  <li *ngFor="let product of products$ | async">{{product.name}}</li>
</ul>

HERE IS A DEMO 同样