简体   繁体   English

Angular - 如何延迟 HTTP 请求

[英]Angular - How to delay HTTP Requests

I have an application that loops through an array and makes an API call for each object in the array.我有一个循环遍历数组并为数组中的每个 object 调用 API 的应用程序。 The issue is all of the requests are being fired at once.问题是所有请求都被同时触发。 The delay operator is completly ignored.延迟运算符被完全忽略。

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

If you just want to add fixed delay of 5s for every request, then this might help you如果您只想为每个请求添加 5 秒的固定延迟,那么这可能对您有所帮助

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM