来自 API 的搜索栏自动完成 [英] Search bar Autocomplete from API

查看:20
本文介绍了来自 API 的搜索栏自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有自动完成功能的图书搜索栏,每次按键都会动态显示相关结果.一切正常,我正在获取数据,但下拉菜单中未显示结果

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 results are not showing on the dropdown menu

使用 angular 8 和 Material 8.2.3

Using angular 8 and Material 8.2.3

我正在尝试创建一个带有自动完成功能的图书搜索栏,每次按键都会动态显示相关结果.一切正常,我正在获取数据,但下拉菜单中未显示结果

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 results are not showing on the dropdown menu

    import { Component, OnInit } from '@angular/core';
    import { Store } from '@ngrx/store';
    import { AppState } from '../app.state/app.state';
    import { Observable } from 'rxjs/Observable';
    import { UserName } from '../../model/name.model';
    import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
    import { MainService } from '../main.service';
    
    @Component({
      selector: 'app-search',
      templateUrl: './search.component.html',
      styleUrls: ['./search.component.css']
    })
    export class SearchComponent implements OnInit {
      searchForm: FormGroup;
    
      username: Observable<UserName[]>;
      searchTerm: string;
      searchResult: [];
      isLoading = false;
      errorMsg: string;
    
      constructor(private store: Store<AppState>, private searchService: MainService, private formBuilder: FormBuilder) {
        this.username = store.select('username');
       }
    
      ngOnInit() {
        this.searchForm = this.formBuilder.group({
          searchBar: ''
        });
        this.onChanges();
      }
    
      onChanges(): void {
        this.searchForm.get('searchBar').valueChanges.subscribe(val => {
          this.searchService.searchingValue(val).subscribe(function(data){
            this.searchResult = data.items;
          } );
    
        });
    
      }
     
      }

    <!-- <p>{{ username.username }}</p> -->
    <h1>Book Search</h1>
    <form [formGroup]="searchForm">
        
            <!-- <mat-form-field>
                 <input type="text" matInput formControlName="searchBar" [matAutocomplete]="auto">
            </mat-form-field> -->
    
                <mat-form-field>
                    <input matInput placeholder="Search" aria-label="State" [matAutocomplete]="auto"  formControlName="searchBar">
                    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
                      <mat-option *ngIf="isLoading" class="is-loading">Loading...</mat-option>
                      <ng-container *ngIf="!isLoading">
                        <mat-option *ngFor="let option of searchResult" [value]="option">
                          <span>{{ option.volumeInfo.title }}</span>
    
                        </mat-option>
                      </ng-container>
                    </mat-autocomplete>
                  </mat-form-field>
              
            
    </form>

推荐答案

总体工作,您可以在此StackBlitz 链接

onChange() 方法 首先,您必须通过管道 () 对所有 rxjs 运算符(如 filter、debounceTime、switchMap)进行管道传输.这里当文本输入改变时,你可以先检查 valueChanges,然后在 switchMap() 中你可以触发服务 api 调用数据.

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<{}>; 
   })
}

这里,

  • 第一个 pipe() 运算符是 filter(),用于过滤用户输入的任何黑色空间.所以,没有什么需要 api 请求.
  • 第二个 pipe() 运算符是 debounceTime(500),用于等待停止用户输入.并且恰好在 5ms 搜索字符串被传递给 switchMap() 的 api 请求之后
  • 第三个 pipe() 操作符是 switchMap(),用于在每次 valueChanges 之后切换到一个新的 observable.
  • 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 ));
}

这篇关于来自 API 的搜索栏自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆