angular+ts 实现函数防抖

2023-02-19  本文已影响0人  饱饱抓住了灵感
  1. user-form.component.html页面, 为nz-select组件设置搜索函数(nzOnSearch)="searchUserData($event)"
  <nz-spin [nzSpinning]="loading"></nz-spin>
  <nz-select name="userName" nzAllowClear nzShowSearch [(ngModel)]="selectedUser" required #UserName2="ngModel" nzPlaceHolder="请输入名称搜索"  style="width: 100%"
        (nzOnSearch)="searchUserData($event)">
        <nz-option *ngFor="let user of UserData" [nzValue]="user" [nzLabel]="user.name"></nz-option>
  </nz-select>
  1. UserComponent.ts, 将搜索值加入队列, 并设置队列消费事件, 其中debounceTime(600)表示600毫秒无连续输入才触发
import {OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';

@Component({
  templateUrl: './user-form.component.html'
})
export class UserComponent implements OnInit{
  userData:User[] = [];
  private searchQueue$ = new Subject<string>();
  loading: boolean;
  
  constructor(private userService: UserService) {
    }

  ngOnInit(): void {
    this.searchQueue$.pipe(
        debounceTime(600),
        distinctUntilChanged(),
        switchMap(value => {
          this.loading = true;
          return this.userService.listUserByName(value);
        }
  )).subscribe(json => {
      this.loading = false;
      if (json.returnCode == 1) {
        this.userData = json.content;
      } else {
        this.message.error('请求失败,请重新输入');
      }
    });

  }

  searchUserData (value: string) {
    this.searchQueue$.next(value);
  }
  
}
  1. UserService.ts, 将搜索值传至后端, 若参数为空, 则直接返回Observable对象
import {HttpClient, HttpParams} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {JsonResponse} from "../../../base/domain/json-response";
import {Observable, of} from 'rxjs';

@Injectable()
export class UserService {
    constructor(private http: HttpClient) {
    }

    listUserByName(name:string):Observable<JsonResponse<any>> {
        if (!name) {
            let jsonResponse = new JsonResponse<any>();
            jsonResponse.returnCode = 1;
            jsonResponse.content = [];
            // 错误用法 return new Observable(() => jsonResponse);
            return of(jsonResponse);
        }
        let httpParams = new HttpParams().set("name", name);
        return this.http.post<JsonResponse<any>>('/userApi/listUserByName', httpParams);
    }

}
上一篇 下一篇

猜你喜欢

热点阅读