【问题标题】:Typescript foreach() with async http request带有异步 http 请求的打字稿 foreach()
【发布时间】:2019-04-26 19:59:51
【问题描述】:


我的角度 webapp 有问题。 我正在尝试遍历一个数组,并每次发出 HTTP 请求以获取Module 的 ID,这是一个对象:
{name:string, charge:string} 一旦我用新的属性id 更新了每个模块,我想用这些 ID 做一些事情。为此,我需要所有 ID,并且无法单独处理每个 Module。我该如何做到这一点?我知道,因为 Angular 中的 http.get() 函数是异步的,所以我不能简单地将代码粘贴到 foreach() 循环之后。

这是我的代码:

ngOnInit() {
let fit = parseFit(megafit.default.fit);
fit.modules.forEach(Module => {
  this.http.get(`https://esi.tech.ccp.is/v2/search/?categories=inventory_type&search=${Module.name}&strict=true`)
  .subscribe((data:any) => {
    Module.id = data.inventory_type
  })
});
//Do smth. with all the IDs 

}

此致,
一月

【问题讨论】:

    标签: angular typescript asynchronous foreach


    【解决方案1】:

    使用承诺而不是订阅者

    ngOnInit() {
    let fit = parseFit(megafit.default.fit);
    const jarOfPromises =[];
    fit.modules.forEach(Module => {
    jarOfPromises.push(
      this.http.get(`https://esi.tech.ccp.is/v2/search/?categories=inventory_type&search=${Module.name}&strict=true`)
      .toPromise())
    });
    
    Promise.all(jarOfPromises).then(results=>{
    /** your code **/
    });
    

    请注意,这是我在手机上写的?

    【讨论】:

    • 为什么 OP 应该使用 promises 而不是 observables?
    • 这只是实现他/她所要求的一种方式。在这种情况下,我认为使用 Promise 比使用更复杂的 RXJS 操作符更容易
    【解决方案2】:

    你需要一些 RxJS 操作符才能做到这一点。

    使用fromModule[] 转换为Observable<Module> 然后将流通过管道传输到mergeMap 并执行api 请求。使用 tap 使用 API 的结果更改您的模块对象,最后使用 toArray 收集响应。订阅流以在处理所有模块时执行您想要执行的操作。

    示例:

    from(fit.modules).pipe(
        mergeMap(module => this.http.get(...).pipe(
            tap(apiResponse => module.id = apiResponse.inventory_type)
        )),
        toArray()
    ).subscribe(allResponses => {
        // do your action
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 2014-09-01
      • 2020-02-18
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多