1

How can i get qLength in this :

var intervalPromise = $interval( function (){
    $http.get(request).success(function (datatemp) {                    // Get Queue info JSON every 2s
        if (angular.equals(store.queues, datatemp)) {               //if like the last, no change
            console.log('Same values');
            qLength =  store.queues.Jobs.length;
        } else {                                                    //Else, update
            store.queues = datatemp;
            console.log('Values updated')
        }
    });
}, 3000, 0);

console.log(qLength);

console.log(qLength) return undefined.

When i try using window, it's same result.

Pierolain
  • 189
  • 1
  • 3
  • 18

2 Answers2

0

you have missed assign variable for qLength

try this below code

**var qLength="";**
var intervalPromise = $interval( function (){
    $http.get(request).success(function (datatemp) {                    // Get Queue info JSON every 2s
        if (angular.equals(store.queues, datatemp)) {               //if like the last, no change
            console.log('Same values');
            qLength =  store.queues.Jobs.length;
        } else {                                                    //Else, update
            store.queues = datatemp;
            console.log('Values updated')
        }
    });
}, 3000, 0);

console.log(qLength);
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

You can't get qLength in this manner because the $interval() and the $http.get() request are running in an asynchronous manner. You're trying to access a value that can only be accessed asynchronously in a synchronous manner. A simple way to get the value you're looking for is to create a function that accepts the length itself and have it invoked when the request has been fulfilled.

var qLengthCheck = function(length) {
  // This logs the length in each interval
  console.log(length);
};

var intervalPromise = $interval( function (){
    $http.get(request).success(function (datatemp) {                    // Get Queue info JSON every 2s
        if (angular.equals(store.queues, datatemp)) {               //if like the last, no change
            console.log('Same values');
            qLength =  store.queues.Jobs.length;
        } else {                                                    //Else, update
            store.queues = datatemp;
            console.log('Values updated')
        }

        qLengthCheck(length);
    });
}, 3000, 0);

If you're having trouble about asynchronous processes, you can check this good non-programming example in this stackoverflow answer

Community
  • 1
  • 1
ryeballar
  • 29,658
  • 10
  • 65
  • 74
  • Thanks for your explanation and solution. If i understand well, i need to use my length variable when it has been defined but not before, neither outside bloc (or i should use your solution). – Pierolain Mar 10 '15 at 10:46