Search bar Autocomplete from API

后端 未结 2 1840
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 14:35

I\'m trying to create a book search bar with autocomplete that will show relevant results dynamically with each keypress. Everything is working and I\'m getting the data, but re

2条回答
  •  生来不讨喜
    2021-01-26 15:11

    Total working, example you can find out here in this StackBlitz Link

    onChange() method you have to pipe () first of all rxjs operators like filter, debounceTime, switchMap. here when text input is changed you can check valueChanges first and then in switchMap() you can fire services api calling of data.

    onChanges(){
       this.searchForm.get('searchBar').valueChanges.pipe(
          filter( data => data.trim().length > 0 ),
          debounceTime(500),
          switchMap(  (id: string) => {
             return id ? this.serachService.searchingValue(id.replace(/[\s]/g,'')) : of([]);
          })
       ).subscribe(data =>{
          this.searchResult = data as Array<{}>; 
       })
    }
    

    here,

    • first pipe() operator is filter(), used for filter any black spaces entering by user. so, that nothing calls for api requesting.
    • second pipe() operator is debounceTime(500), used for waiting to stop user typing. and exactly after 5ms search string is passed on api request of switchMap()
    • Third pipe() operator is switchMap(), used to switch to a new observable, after every valueChanges.

    search.service.ts

    searchingValue(value){
        return of(this.bookDetails.filter( booksName => booksName.name.replace(/[\s]/g,'').toLowerCase().indexOf(value.toLowerCase()) === 0 ));
    }
    

提交回复
热议问题