简体   繁体   English

Angular如何使订阅等待呼叫完成

[英]Angular How to make subscribe wait for a call to finish

INSERT NOTE: This question is not the same as most of the other questions relating to stuff like "How do I return the response from an asynchronous call?" 插入注:此问题与其他大多数与“如何从异步调用返回响应?”之类的问题不同。 because of the fact that it uses SUBSCRIBE. 因为它使用SUBSCRIBE。 As far as I understand it, subscribe tells it to do something whenever this thing is changed, therefore you cannot put code inside the subscribe, because it will only ever run when it gets changed (which will always be too late). 据我了解,subscribe告诉它每当发生更改时就执行某项操作,因此您不能将代码放入subscribe中,因为它只有在更改时才会运行(永远为时已晚)。 Please only answer if you have knowledge of Angular, Subscribe and the HttpClient. 仅当您了解Angular,Subscribe和HttpClient时,才回答。 Now my original question: 现在我的原始问题是:

I have a problem where I loop through an array and do a get call for each item in the array. 我有一个问题,我遍历一个数组并对数组中的每个项目进行get调用。 My problem is that all these get requests happen asynchronously, which means they all try to get while the previous gets are still receiving their responses. 我的问题是所有这些获取请求都是异步发生的,这意味着它们都试图在先前的获取仍在接收其响应的同时获取。 This causes an error. 这会导致错误。 Here is a rough example: 这是一个粗略的示例:

 this.MyArray = [1, 2, 3, 4, 5];   

 this.MyArray.forEach(element => {
      this.httpClient.get('http...')
      .subscribe(
        (response: any) => {
      })
 )}

How do I let the forEach loop wait for the call response before moving on to the next item in the loop? 我如何让forEach循环在进入下一个项目之前等待呼叫响应? I tried looking at responses but I just can't understand it :( 我尝试查看回复,但我听不懂:(

You can map your array into observable streams. 您可以将数组映射到可观察的流中。 Then you can use concat operator to execute the observables in a row. 然后,您可以使用concat运算符连续执行可观察对象。

import {
  concat
} from 'rxjs/observable/concat';


this.MyArray = [1, 2, 3, 4, 5];

const observables: Observable<any>[] = this.myArray.map(() => this.httpClient.get('http...'));

concat(...observables).subscribe(resp => {
  // handle responses, they will execute one after another,
  //  each waiting for the previous one to finish
})

Try this 尝试这个

this.totalCount = this.MyArray.length;
this.i=1;

getData(){

 let ob = this.MyArray[this.i-1];

 this.httpClient.get('http...')
      .subscribe(
        (response: any) => {
            this.i++;
             if(this.i <= this.totalCount){
               getData()
             }
      })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM