Search code examples
async-awaitangular5httpclientdelay

Angular 5 continue iteration, when we get response


I have a situation. I have a for loop. I am sending each object information to service and getting response back from the service.

I want to pause the for loop and continue once the http client return the response. Here is my service code :

.ts file

 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);
            }
        );



    }

Service method :

 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;

    });

}

So, once the first iteration gives response, then the second iteration should start. Point me out with an example.


Solution

  • Try recursive function call instead for loop, watch after each success and then call function again, Set one base case (i.e. call recursively unless and until it reaches to end of loop)

    Try this:

    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
      })
    }