Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Send $http.get requests continuously until certain condition

As the title says, I want to send $http.get requests to the server until the returned results meets a condition.

This is what I tried:

    var searchComplete = false;
    var sendGetReq = true;

    while(!searchComplete) // #2 and then jumps here
    {
       if(sendGetReq)
       {
         sendGetReq = false;  // #1 execution reaches here
         $http.get('/user/getCondition', {params: {condition: $scope.condition}).
        success(function (condition, status, headers, config) {
         ...
         ...
         if(condition)
         { searchComplete = true; }
         else
         { sendGetReq = true; }
    }
}

However, the $http.get request never goes. That statement is never reached. When I debugged, I saw that execution will come to sendGetReq=false and then jump to while(!searchComplete). The GET request is never sent.

Would someone please explain:

  1. Why the execution never reaches GET request and jumps back
  2. What is the recommended way to to do this continuous GET request

Thank you.

like image 322
madu Avatar asked Sep 18 '26 11:09

madu


1 Answers

Why not put it all together inside a function and call itself if condition is meet? Like this and you should use .then and not .success:

$scope.load = function(){
  $http.get('/user/getCondition', {params: {condition: $scope.condition}).
    then(function (condition, status, headers, config) {

    if (condition){
       $scope.load();
    }

  });
}

Hope it helps =)

like image 54
Gustavo Gabriel Avatar answered Sep 20 '26 03:09

Gustavo Gabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!