【问题标题】:Angular 7 Ng2SmartTable cancel previous search requestsAngular 7 Ng2SmartTable 取消以前的搜索请求
【发布时间】:2019-08-22 19:13:47
【问题描述】:

我使用的是 Angular 7.0.1 版和 ng2-smart-table 1.4.0 版。 每当我在表中搜索时,都会向 api 发送一个请求以检索相应的数据。但是,每次搜索都是一个新请求,我只希望最新的请求通过并取消之前的(仍待处理的)请求。

HTML 代码:

<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>

我的数据源类:

export class DataSource extends LocalDataSource {

  protected conf: ServerSourceConf;
  private lastRequestCount = 0;

  constructor(conf: ServerSourceConf | {} = {}, private service: DataServiceService) {
    super();

    this.conf = new ServerSourceConf(conf);
    this.conf.totalKey = 'total';
  }

  count() {
    return this.lastRequestCount;
  }

  getElements(): Promise<any> {
    return this.requestElements().map(res => {
      this.lastRequestCount = this.extractTotalFromResponse(res);
      this.data = this.extractDataFromResponse(res);
      return this.data;

    }).toPromise();
  }

  /**
   * Extracts array of data from server response
   * @param res
   * @returns {any}
   */
  protected extractDataFromResponse(res: any) {
    const rawData = res;
    const data = !!this.conf.dataKey ? getDeepFromObject(rawData, this.conf.dataKey, []) : rawData;

    return data;
  }

  /**
   * Extracts total rows count from the server response
   * Looks for the count in the heders first, then in the response body
   * @param res
   * @returns {any}
   */
  protected extractTotalFromResponse(res: any) {
      const rawData = res;
      return getDeepFromObject(rawData, this.conf.totalKey, 0)
  }

  protected requestElements(): Observable<any> {
    return this.service.getData(this.conf.endPoint, this.createRequestOptions());
  }

  protected createRequestOptions() {
    let httpParams: HttpParams = new HttpParams();

    /**
     * Add Sorting to http parameters
     */
    this.addSortRequestOptions().forEach(function(row, key){
      httpParams = httpParams.set(row.key, row.value);
    });

    /**
     * Add page to http parameters
     */
    this.addPagerRequestOptions().forEach(function(row, key){
      httpParams = httpParams.set(row.key, row.value);
    });

    /**
     * Add filters to http parameters
     */
    this.addFilterRequestOptions().forEach(function(row, key){
      httpParams = httpParams.set(row.key + '_like', row.value);
    });
    return httpParams;
  }

  protected addSortRequestOptions() {
    const params = [];

    if (this.sortConf) {
      this.sortConf.forEach((fieldConf: any) => {
          params.push({key: this.conf.sortFieldKey, value: fieldConf.field});
          params.push({key: this.conf.sortDirKey, value: fieldConf.direction.toUpperCase()});
      });
    }
    return params;
  }

  protected addFilterRequestOptions() {
    const params = [];

    if (this.filterConf.filters.length !== 0) {
      this.filterConf.filters.forEach((fieldConf: any) => {
        if (fieldConf['search']) {
          params.push({key: fieldConf['field'], value: fieldConf['search']});
        }
      });
    }
    return params;
  }

  protected addPagerRequestOptions() {
    const params = [];

    if (this.pagingConf && this.pagingConf['page'] && this.pagingConf['perPage']) {
      params.push({key: this.conf.pagerPageKey, value: this.pagingConf['page']});
      params.push({key: this.conf.pagerLimitKey, value: this.pagingConf['perPage']});
    }
    return params;
  }
}

数据服务.服务:

import {Injectable} from '@angular/core';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {

  url = environment.server;

  constructor(private http: HttpClient) { }

  getData(endpoint: string, options?: any) {
    return this.http.get(this.url + endpoint, {params: options}).pipe();
  }
}

【问题讨论】:

    标签: angular typescript ng2-smart-table


    【解决方案1】:

    尝试使用switchMap()。它取消了之前的请求。

    getElements(): Promise<any> {
        return this.requestElements().switchMap(res => {
          this.lastRequestCount = this.extractTotalFromResponse(res);
          this.data = this.extractDataFromResponse(res);
          return of(this.data);
    
        }).toPromise();
    }
    

    你确定你使用的是旧版本的 RxJS,所以你在没有pipe() 的情况下使用它吗? 像这样的:

    getElements(): Promise<any> {
        return this.requestElements().pipe(switchMap(res => {
          this.lastRequestCount = this.extractTotalFromResponse(res);
          this.data = this.extractDataFromResponse(res);
          return of(this.data);
        })).toPromise();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      相关资源
      最近更新 更多