首页 > 解决方案 > 如何迭代一组值并调用返回承诺的服务并等待Angular 6中的每个结果

问题描述

我有一个 Angular 6 项目,我在其中获得了一个字符串数组,并且需要使用数组中的每个项目调用后端服务。

组件代码(简化)如下所示:

items: any[] = ['one','two','three']

for (let item of this.items) {
    this.dataSvc.searchItems(item)
    .subscribe(
        data => {
            console.log(item, data);
        })
}

Angular 服务代码如下:

public searchItems(item: string): Observable<any> {
        let params = new HttpParams();

        params = params.append('item', item);

        return = this.httpClient.get(SERVER_API, { params: params })
}

这适用于数组中的单个项目,但是当数组扩展时,服务开始抛出超时错误,并返回一些但不是全部结果。

我之前在与这个后端交互时遇到过问题,在其他我有一个不会改变的固定项目列表的领域,我已经在代码中链接了一系列静态的 Promise,这样我每次都等待调用服务直到以前的结果又回来了,但是我不确定如何在循环中完成同样的事情。

这就是我在组件中使用 Promise 包装器在其他地方使用 Promise 链进行管理的方式:

fetchService(item): Promise<any> {
    return this.dataSvc.searchItems(item)
        .toPromise();
}

this.fetchService('one')
    .then(data => {
        console.log("one", data);
        return this.fetchRegCodeLit('two')
    }).then(data => {
        console.log("two", data);
        return this.fetchRegCodeLit('three')
    }).then(data => {
        console.log("three", data);
    })

items 数组是动态的,它可能包含 10 或 100 个项目,我需要能够将每个项目传递给同一个服务,并保证我已经收到响应并在再次调用服务之前对其进行处理,但我可以' t似乎弄清楚如何。

我一直在研究 async/await,我认为这就是解决方案所在,但是我尝试过的任何代码排列都会导致编译错误,所以我显然遗漏了一些东西。

标签: angulartypescriptiteratorasync-awaitobservable

解决方案


使用toPromise()可能是件好事。您可以并行运行所有内容并使用Promise.all()等待结果。

items: any[] = ['one','two','three']

//list of http promise
const itemsSearchPromise = [];

for (let item of this.items) {
   itemsSearchPromise.push(this.dataSvc.searchItems(item).toPromise());
}

Promise.all(itemsSearchPromise).then( (datas) => {
  //datas is an array of every result in the order of the "itemsSearchPromise"
}

推荐阅读