2

I am using the method based on this answer: Server polling with AngularJS

But how can I set this update when I have multiple polling methods?

Here is a snippet of my service:

function pollingService($resource) {
    return {
        methodA: $resource(window.rootUrl + 'api/methodA', { para: '@para1' }, {
            query: { method: 'GET', params: {}, isArray: false }
        }),
        methodB: $resource(window.rootUrl + 'api/methodB', {}, {
            query: { method: 'GET', params: {}, isArray: false }
        })
    }
};

So how can I set up the tick method to poll theese 2 methods and only create 1 polling loop?

(function tick() {
    $scope.method1 = pollingService.methodA.query(function () {
        $timeout(tick, $scope.refreshRate);
    });
    $scope.method2 = pollingService.methodB.query(function () {
        $timeout(tick, $scope.refreshRate);
    });
})();
Community
  • 1
  • 1
stibay
  • 1,200
  • 6
  • 23
  • 44

2 Answers2

2

You could use the promises $q.all function:

var myTickFunc = function() {
  return $q.all([pollingService.methodA.query().$promise, pollingService.methodA.query().$promise)
     .then(function(result){ 
            //Setup timer again
});
Noel
  • 3,288
  • 1
  • 23
  • 42
  • That seem to work pretty nice, only issue is the mapping of the results though. Do you just map the result[id] to the number of when the promise was added? so the first one will be result[0], second result[1] etc. Or is it any better way of mapping this? – stibay Dec 07 '15 at 13:50
  • The result from `methodA` will come first, then `methodB`. In the same order as you add the `promises` to the `array` passed to `$q.all()`. – Arg0n Dec 07 '15 at 13:51
  • Yep, exactly. The results come back as an array in this example. – Noel Dec 07 '15 at 13:53
1

Using $q.all()

(function tick() {
    var promises = [];
    promises.push(pollingService.methodA.query().$promise);
    promises.push(pollingService.methodB.query().$promise);
    $q.all(promises).then(function(results){
        var result1 = results[0]; //Result from methodA
        var result2 = results[1]; //Result from methodB
        $timeout(tick, $scope.refreshRate);
    }
})();
Arg0n
  • 8,283
  • 2
  • 21
  • 38
  • Yea, I actually concidered that. But didn't know if that was "the angular way" and if it was an easier way instead of doing it. – stibay Dec 07 '15 at 13:33
  • Well, if i would write the code, i would use `promises` and then do `$q.all(promises).then(function(){ //Code });` – Arg0n Dec 07 '15 at 13:34
  • Is it possible to access the promise element while it's "loading" the data? With my previous method I could access method1.$resolved in my view and it would dynamicly change between true and false when the promise was called. – stibay Dec 07 '15 at 14:33
  • I guess you can assign them to separate variables: `var query1 = pollingService.methodA.query()` `promises.push(query1.$promise)` `query1.$resolved; //What you want` – Arg0n Dec 07 '15 at 14:36