首页 > 解决方案 > 从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?

标签: angularhttpobservable

解决方案


永远订阅!

直到您对该方法返回的可观察对象调用 subscribe() 后,HttpClient 方法才会开始其 HTTP 请求。这适用于所有 HttpClient 方法。

参考链接


推荐阅读