3

特定のクエリに基づいてオブジェクトの配列を除外するパイプを作成しました。それはうまく機能しますが、可能であれば、入力のキーアップイベントに追加するのではなく、このパイプに直接デバウンス機能を追加したいと考えています。

解決策を探していますが、探しているものに固有のものを見つけることができないようです。

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'filterBy'
})

export class FilterByPipe implements PipeTransform {

  transform(value: any, args: string[]): any[] {

    if (!args[0]) {
      return value;
    }
    else if (value) {

      return value.filter(item => {

        // TODO: Allow args[1] to be null, therefore searching in all object properties
        if ((typeof item[args[1]] === 'string' || item[args[1]] instanceof String) && (item[args[1]].toLowerCase().indexOf(args[0].toLowerCase()) !== -1)) {
          return true;
        }
      });
    }
  }
}

このパイプでこれをどのように実装するかについてのアイデアはありますか?

4

2 に答える 2

3

デバウンスまたは遅延関数は非同期です。この場合、パイプからプロミスまたはオブザーバブルを返し、非同期パイプを使用する必要があります。Observable でそれを行う方法を示す簡単な例を作成しました。

@Pipe({
    name: 'myfilter'
})

export class MyFilterPipe implements PipeTransform {
    transform(items, filterBy) {
      const filteredItems = items.filter(item => item.title.indexOf(filterBy.title) !== -1);
      return Observable.of(filteredItems).delay(1000);
    }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <ul>
        <li *ngFor="let item of items | myfilter:filterBy | async">
         {{item.title}}
        </li>
      </ul>

      <input type="text" (input)="filter($event)">

    </div>
  `,
})
export class App {
  filterBy;
  constructor() {
    this.filterBy = {title: 'hello world'};
    this.items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
  }

  filter($event) {
    this.filterBy = {title: $event.target.value}
  }
}

プランカー

于 2016-10-31T09:29:16.790 に答える