Typescript - 迭代内的订阅

Typescript - subscription inside iteration

我试图为“myArray”变量中的每个值一遍又一遍地调用“getData”API。每次它从“getData”调用获取新数据时,我都试图将结果推送到一个数组中,这样我就可以在代码的“destinationArray”部分中操作这些值。但是,由于打字稿不是异步的,它会在完成迭代之前在 .subscribe / 中完成“destinationArray”代码。

我已经尝试用 await waitUntil(() => done==true, { timeout: 10015 }); 解决这个问题 但我不断在控制台中收到随机出现的消息 ERROR Error: Uncaught (in promise): Error: Timed out after waiting for 10015 ms。天真的答案是将超时增加到无穷大,但实际 API 调用本身并不需要 10 秒,大约需要 1 秒(即使那么长)。 我怎样才能让它等到它完成迭代/订阅后再移动到底部的“destionationArray”部分,而不在控制台中看到超时错误消息?

let dataFromAPIcall: any[] = []
let myArray: any[] = ["hello","world"]
for(let i = 0; i< myArray.length; i++) {    
    this.GetDataSubScription = this.myService.getData(myArray[i]).pipe( takeUntil(this.ngUnsubscribe) ).subscribe(data => {
        dataFromAPIcall.push(data)
        if(i+1 == myArray.length) {
            done = true
        }
    });
}

await waitUntil(() => done==true, { timeout: 10015 });
                    
let destinationArray: any[] = [];
for(let i = 0; i < dataFromAPIcall.length; i++) {
    destinationArray[i] = [dataFromAPIcall[i].something1, dataFromAPIcall[i].something2]
}

您可以 zip 您的 api 调用并以反应方式处理所有响应,而无需使用命令式状态变量:

After all observables emit, emit values as an array

// creating an array of observables. The requests are not fired yet.
const requests = myArray.map(i => this.myService.getData(i));
const destinationArray: any[] = [];

// passing the request array to the zip function.
// this will actual initiate the requests and emit when ALL
// requests are done
zip(...requests).pipe(
  tap(responses => {
      // maping responses to destinationArray
      destinationArray = responses.map(dataFromAPIcall => [dataFromAPIcall.something1, dataFromAPIcall.something2])
  }),
  tap(_ => {
    // continue here
  })
).subscribe();