javascript - 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));
}
解决方案
如果您只想为每个请求添加 5 秒的固定延迟,那么这可能会对您有所帮助
const all = [1,2,3,4,5];
all.forEach((each, i) => {
setTimeout(() => {
console.log(each); // Call your http request
}, i * 5000)
});
推荐阅读
- c++ - 如何在 C++ 中使用接口
- clojure - Clojure 哈希算法
- c++ - 在 switch 语句中分配 lambda
- c# - 扩展动态调度以调用视图模型中的函数?
- firebase - 如何将firebase配置为nuxt插件?
- c-preprocessor - 在 Doxygen 中记录条件独占代码
- python - 使用 AdamOptimizer 继续训练自定义 tf.Estimator
- javascript - React Native 等待所有图像预取完成
- php - Laravel关系并获取第三张表的数据
- python - 如何修复“单例数组 array(0) 不能被视为有效集合。”