数组 map 中发送异步请求案例

2021-07-31  本文已影响0人  云上笔记

有个 table 页面如下,数据需要请求同一个接口五次(入参不同), 然后把五次请求到的数据合并到一个表格中,并使用同一个翻页


table.png

这里需要解决的问题有:
1.同时发送多个异步请求,且请求和响应的顺序保持一致;
2.找到响应数据中总条数最多的那个,以此为长度基准生成表格数据;
3.获取表格中每一列需要的数据,生成数组;

对于第一点,可以定义一个包含请求参数的数组,然后在数组 map 方法中发送异步请求

  public quoteList = [
    {
      name: 'Bond price',
      label: ProductTypeText.BOND,
      total_count: 0
    },
    {
      name: 'FX spot',
      label: ProductTypeText.FX_SPOT,
      total_count: 0
    },
    {
      name: 'Commodity',
      label: ProductTypeText.COMMODITY,
      total_count: 0
    },
    {
      name: 'Commodity Future',
      label: ProductTypeText.COMMODITY_FORWARD,
      total_count: 0
    },
    {
      name: 'Equity freqyure',
      label: ProductTypeText.EQUITY_OPTION,
      total_count: 0
    },
  ];

  /**
   * 发送单个异步请求
   */
  private requestQuote(productType?): Promise<any> {
    const params = {
      mdsi_quote: {
        page: this.quotePagination.pageIndex,
        size: this.quotePagination.pageSize,
        reference_date: this.datePipe.transform(this.referenceDate, 'yyyy-MM-dd'),
        create_time: this.datePipe.transform(this.createTime, 'yyyy-MM-ddTHH:mm:ss'),
        product_type: productType
      }
    };
    this.quoteLoading = true;
    return new Promise((resolve, reject) => {
      this.shareDataService.requestSendMessage(params).subscribe(
        res => {
          this.quoteLoading = false;
          if (res.code === '0') {
            resolve(res.mdsi_quote);
          } else {
            reject();
          }
        },
        err => {
          this.quoteLoading = false;
          reject(err);
        }
      );
    });
  }

  /**
   * Promise.all 发送多个请求
   */
  private asyncGetQuoteData(arr) {
    // 某个请求失败,确保其他请求能成功返回
    const promises = [...arr.map(item => this.requestQuote(item.label))];
    return Promise.all(promises.map((promise) => promise.catch(e => {
      console.error(e);
    })));
  }

得到异步响应结果集之后,把数据转换为前端展示所需的格式

  private getQuoteData() {
    // 翻页时清空前一页的数据
    this.formatQuoteList = [];
    // 结果集
    this.asyncGetQuoteData(this.quoteList).then((res: any) => {
      this.quoteList.map((item, index) => item.total_count = res[index]?.total_count);
      // 拷贝结果集,获取排序数组
      const cloneRes = JSON.parse(JSON.stringify(res));
      // 找出条数最多的一列
      const maxQuoteList = cloneRes.sort((a, b) => b.total_count - a.total_count)[0];
      const quoteList = maxQuoteList?.quote_list;
      // 最大页数赋值
      this.quotePagination.total = maxQuoteList?.total_count || 0;
      if (quoteList) {
        quoteList.product.map((product, index) => {
          const obj = {
            bondName: res[0]?.quote_list?.product[index]?.key,
            bondValue: res[0]?.quote_list?.product[index]?.value,
            fxSpotName: res[1]?.quote_list?.product[index]?.key,
            fxSpotValue: res[1]?.quote_list?.product[index]?.value,
            commodityName: res[2]?.quote_list?.product[index]?.key,
            commodityValue: res[2]?.quote_list?.product[index]?.value,
            commodityFutureName: res[3]?.quote_list?.product[index]?.key,
            commodityFutureValue: res[3]?.quote_list?.product[index]?.value,
            EquityfreqyureName: res[4]?.instance_quote?.product[index]?.key,
            EquityfreqyureValue: res[4]?.quote_list?.product[index]?.value,
          };
          this.formatQuoteList = [...this.formatQuoteList, obj];
        });
      }
    }).catch(
      err => {
        console.error(err);
      }
    );
  }

HTML 展示

 <nz-table #bondPriceTable class="tiny-table mr-10" 
                        [nzData]="formatQuoteList" nzSize="small"
                        [nzTotal]="quotePagination.total" [nzPageSize]="quotePagination.pageSize"
                        [nzScroll]="{x: 'auto'}" [nzFrontPagination]="false" 
                        [nzLoading]="quoteLoading"
                        [nzPageIndex]="quotePagination.pageIndex" 
                        (nzPageIndexChange)="quotePageIndexChange($event)">
                        <thead>
                            <tr>
                              <!-- 动态生成表格标题行 -->
                                <ng-container *ngFor="let item of quoteList">
                                    <th class="text-nowrap">{{ item.name }}</th>
                                    <th class="text-right">{{ item.total_count }}</th>
                                    <th nzWidth="10px" class="split"></th>
                                </ng-container>
                            </tr>
                        </thead>
                        <tbody>
                            <tr *ngFor="let list of bondPriceTable.data">
                                <td>{{ list?.bondName }}</td>
                                <td class="text-right">{{ list?.bondValue | number: '1.4-4'}}</td>
                                <td class="split"></td>
                                <td>{{ list?.fxSpotName }}</td>
                                <td class="text-right">{{ list?.fxSpotValue | number: '1.4-4'}}</td>
                                <td class="split"></td>
                                <td>{{ list?.commodityName }}</td>
                                <td class="text-right">{{ list?.commodityValue | number: '1.4-4'}}</td>
                                <td class="split"></td>
                                <td>{{ list?.commodityFutureName }}</td>
                                <td class="text-right">
                                     {{ list?.commodityFutureValue | number: '1.4-4'}}
                                </td>
                                <td>{{ list?.EquityfreqyureName }}</td>
                                <td class="text-right">{{ list?.EquityfreqyureValue | number: '1.4-4'}}</td>
                            </tr>
                        </tbody>
</nz-table>
上一篇 下一篇

猜你喜欢

热点阅读