Как улучшить производительность поискового фильтра в угловых для большого списка - PullRequest
0 голосов
/ 05 мая 2018

при вводе в строке поиска событие мыши приостанавливается на несколько секунд во время набора до загрузки данных (кажется, что каждое событие щелчка запускает данные для загрузки в поиске), это происходит для первых нескольких типов ввода с использованием труба фильтра поиска) без трубы поиска это все еще медленно. Пожалуйста, помогите спасибо Пожалуйста, нажмите на ссылку, чтобы посмотреть пример stackblitz:

https://ionic -6cbe9t.stackblitz.io

searchFilter(searchTerm){
  if(searchTerm != ''){
    searchTerm = searchTerm.toLowerCase();
  }

  if(!this.listFromArray){
    return Immutable.List();
 }

  if(!searchTerm){
    return this.listFromArray;
  }

  return  this.listFromArray.filter((address) => {
    return address.Company.toLowerCase().includes(searchTerm) ||
        address.Phone.toString().includes(searchTerm) ||
        address.Street.toLowerCase().includes(searchTerm) ||
        address.City.toLowerCase().includes(searchTerm)  ||
        address.Phone.includes(searchTerm);
  });
}

1 Ответ

0 голосов
/ 06 мая 2018

Как выполнить поиск "debounceTime"

Ваш компонент.html

  <input #search (keyup)="searchTerm.next(search.value)">
  <div *ngIf="results"> 
    <!--slice is optional-->
    <div *ngFor="let item of results |slice:0:10">
         {{item.descripcion}}
    </div>
   </div>

В вашем компоненте .ts

  //We defined three variables,
  items:any[];  //our items
  results:any[];  //Our items filtered
  searchTerm = new Subject<string>();  //A subject 

  search(terms: Observable<string>) {
    return terms.pipe(debounceTime(400),
      distinctUntilChanged(),
      switchMap(term => this.searchEntries(term)));
  }

  searchEntries(term) {
    //here we can put others conditions to term
    //like term.lenght>3, e.g.
    if (!term)
      return of(null);  //Notice we return an observable -using Observable.of
    term=term.toUpperCase();
    return of(     //Idem before. If we're ask about an observable
                   //Like httpClient.get, we not need "of" 
       this.items.filter(a=>a.searchProperty.indexOf(term)>=0)
    );
  }

  ngOnInit() {
    //we subscribe to get the items
    this.http.get("assets/items.json").subscribe((res:any[])=>{
         //we can do this.items=res ...
         //this.items=res;
         //...but better make a map and create a property "searchProperty"
         //so, our filtered can be over this property. notice
         //the map is executed only one time
         this.items=res.map(x=>{
           return {
                   ...x,
                   searchProperty:x.descriptcion.toUpperCase()
                         +x.texto.toUpperCase()
                         +x.comment.toUpperCase()
                   }
          });
         //then, we subscribe to "this.search"
        this.search(this.searchTerm)
          .subscribe(results => {
             this.results = results;   
        });
    });
}

ПРИМЕЧАНИЕ. Код в значительной степени основан на https://alligator.io/angular/real-time-search-angular-rxjs/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...