首页 > 解决方案 > Angular - 如何延迟 HTTP 请求

问题描述

我有一个循环遍历数组并为数组中的每个对象进行 API 调用的应用程序。问题是所有请求都被立即触发。延迟运算符被完全忽略。

 public StartIt() {

    const len = this.stocks.length;
    console.log(len);

    for (const el of this.stocks) {
      this.iex.getFiveDay(el.Symbol).subscribe((res: any) => {
        console.log(res);
        this.ops.getVolAvg(res);
        this.datax.push(res);

      });



    }
  } 



 public getFiveDay(symbol) {
    const url: any = this.getApiUrl(symbol, iexEndPointType.fiveday);
    console.log('IEX SERVICE - getFiveDay(): ' + url);
    return this.httpClient.get(url).pipe(delay(5000));
  }

标签: javascriptangulartypescriptrxjs

解决方案


如果您只想为每个请求添加 5 秒的固定延迟,那么这可能会对您有所帮助

const all = [1,2,3,4,5];
all.forEach((each, i) => {
    setTimeout(() => {
    console.log(each); // Call your http request
  }, i * 5000)
});

推荐阅读