Monday, October 16, 2017

How to make multiple request in a loop in agularjs2 in Ionic?

I have to copy an online database to offline database using an API call with post method. one API call returns 12 records and number of total records are unknown. To do that I wrote the following code and when I ran it, it never stopped. function should stop when the result is empty. but its not stopping, I think it is the issue with asynchronous nature of JavaScript. Anyone who can suggest a solution. I am new to angularjs and Ionic.

  getProducts()
  {
    var flag = true;
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('token',  this.token);
    let options = new RequestOptions({ headers: headers });
    var body = {"categories":[0],"tags":[0]};
    var productCount = 0;
    while(flag)
    {
        console.log("Products Call");
        var url = "http://url"
        this.http.post(url, body, options)
            .map(res => res.json())
            .subscribe(data => {
                if(data.status == 200)
                {
                    console.log(data.data);
                    console.log(data.data.productsDTOs);
                    console.log(data.data.productsDTOs.length);
                    if(data.data.productsDTOs==[])
                    {
                        console.log("  ", data.data.productsDTOs.length);

                        flag = data.data.productsDTOs.length;
                    }
                    console.log("Length of Products: ",data.data.productsDTOs.length);

                    for(var i=0; i<data.data.productsDTOs.length; i++)
                    {
                        console.log(JSON.stringify(data.data.productsDTOs[i]),data.data[i]);

                        this.category += data.data.productsDTOs[i].id;
                        /* this.category += data.data[i].name;
                         this.category += data.data[i].extAppCategoryid;
                         this.category += data.data[i].displayOnScreen;
                         this.category += data.data[i].description;*/
                       // this.category += "t";

                        //  var id = data.data[i].id;
                        //  var object = JSON.stringify(data.data[i]);
                        // var pid = data.data[i].parentId;
                        //    this.SP.insertCategories(id, object, pid);
                    }
                }
            });
        flag = false;
        productCount = productCount + 12;
    }
}

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/16/how-to-make-multiple-request-in-a-loop-in-agularjs2-in-ionic/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment