【问题标题】:JHipster/Angular: Alternative for pureFilter pipe which was removed (in JHipster 7.0.0.-beta.0)JHipster/Angular:替代已移除的 pureFilter 管道(在 JHipster 7.0.0.-beta.0 中)
【发布时间】:2021-08-28 14:17:54
【问题描述】:

我仍在通过使用 JHipster 6.5.0 的“Full Stack Development with JHipster (Second Edition)”一书学习 JHipster。

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

JHipster 提供的管道,用于使用产品的名称字段过滤列表。

*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 命令的情况下实现所需的过滤?

非常感谢您的支持。

【问题讨论】:

  • 这样的管道由于性能不佳而被移除。在组件中过滤,我推荐 observables,它们是过滤数组的好方法,因为它们不会修改原始数组,否则您需要保留原始数组的副本。你可以自己做烟斗,但我真的不鼓励这样做。

标签: angular jhipster


【解决方案1】:

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

这是一个示例,包括 http。将代码应用于您的用例。我在这里使用了shareReplay 来不为每次搜索触发http-request。 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,记得为你的数组创建一个 observable,你可以使用of(put your array here)

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

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

HERE IS A DEMO 相同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2018-05-27
    • 2023-02-20
    • 1970-01-01
    • 2018-09-20
    • 2019-06-30
    相关资源
    最近更新 更多