angular - 从Angular 2+应用程序中的for循环内部的http调用获取数据
问题描述
我想在 for 循环中调用我的 http 请求,因为我一次只想执行 1000 个项目。所以我有以下代码:
getData(IDs: string[]): Observable<any> {
// IDs is a large array of strings, about 3000 of them
const results = [];
const totalData = [];
// split the IDs array into chunks of 1000
while (IDs.length) {
results.push(IDs.splice(0, 1000));
}
// loop through the new array with the chunks of 1000 and run the http request
for (let i = 0; i < results.length; i++) {
const data = this.http.get(`myhttprequest/${results[i]}`);
totalData.push(data);
}
console.log(totalData);
// this is just an array of observables when I am looking for an array of data
return totalData
}
我没有收到任何错误,但它没有返回数组数据,而是返回了一个可观察的数组。
我知道;因为变量在返回数据之前正在更新,所以我尝试使用 Promise,但不幸的是我无法让它工作。
我怎样才能让这个函数返回数据而不是 observables?
解决方案
永远订阅!
直到您对该方法返回的可观察对象调用 subscribe() 后,HttpClient 方法才会开始其 HTTP 请求。这适用于所有 HttpClient 方法。
参考链接。
推荐阅读
- reactjs - 如何设置具有多个选项的 Material UI Select 组件的 size 属性?
- javascript - Firebase 实时数据库中的云函数
- java - java - 如何使用JavaFX中屏幕的关闭(X)图标关闭用户定义的线程?
- encryption - 将 20 个字符的字符串编码为 8 个字符,并将其解码回来
- mongodb - MongoDB:仅在以前不存在于不同条件下的文档时才返回
- tsql - Rank 语句导致查询运行非常缓慢
- python - 有没有办法使用硒与网页中打开的外部应用程序警报进行交互?
- notepad++ - 使用 Notepad++ 在两个位置同时编辑两个相同的文件
- javascript - 如何在反应中使用formik附加输入
- python - 如何导入子包?