Angular 5 继续迭代,当我们得到响应时

Angular 5 continue iteration, when we get response

我有个情况。我有一个 for 循环。我将每个对象信息发送到服务并从服务获取响应。

我想暂停 for 循环并在 http 客户端 return 响应后继续。这是我的服务代码:

.ts 文件

 for (var j = 0, counter = 0; j < this.actualObj.length; j++) {

    this._custService.placingSingleOrder(this.actualObj[j], this.headerInfo).subscribe(
            (data) => {
                console.log(data);
                counter++;

                if (data.status == "success") {
                    this.sucessOrders.push(data.inserted_order_id);
                    console.log('order inserted success fully........');
                    // this.toastr.success('Order Submitted Succefully !', 'Success!');

                } else if (data.status == "failure") {


                    // this.toastr.error('Order is already present in the database. Please check and try again!', 'Oopssssss!');
                }

                if (counter == this.actualObj.length) {

                    this.updateStatus();

                }
            },
            (error) => {
                counter++
                if (counter == this.actualObj.length) {

                    this.updateStatus();

                }
                //  this.loader = false;
                console.log(error);
            }
        );



    }

服务方式:

 placingSingleOrder(obj, headerInfo) {


    let api_token = sessionStorage.getItem('api_token');
    let email = sessionStorage.getItem('email');
    console.log('before calling serviccccce', headerInfo);
    this.singleOrderHeader = {
        headers: new HttpHeaders({
            'Content-Type': 'text/plain',
            'apitoken': headerInfo.apitoken,
            //'apitoken': 'fkjdhsfhbdsabf',
            'customer_id': headerInfo.customer_id,
            'order_id': headerInfo.order_id
        })


    };
    console.log('before calling serviccccce', this.singleOrderHeader);
    return this.http.post(apiServicesURL + 'api/restapi/Order/addMwwOrder', JSON.stringify({ token: api_token, email: email, Order: obj }), this.singleOrderHeader).map((response: any) => {
        console.log("single order response is: ", response);
        return response;

    });

}

因此,一旦第一次迭代给出响应,则应该开始第二次迭代。用一个例子指出我。

尝试递归函数调用for循环,在每次成功后观察然后再次调用函数,设置一个基本情况(即递归调用,除非并直到它到达循环结束)

试试这个:

const j = this.actualObj.length; // set it global
recursiveFunction(this.j) {
  this._custService
  .placingSingleOrder(this.actualObj[this.j], this.headerInfo)
  .subscribe(data => {
    // your code handler after each success

    this.j--; // decrease operator and call recursive function
    if(this.j) {
      this.recursiveFunction(this.j);
    }
  }, error => {
    // error handler
  })
}