I'm following the angular-poller demo here: https://emmaguo.github.io/angular-poller/
I need to be able to pass an argument into the factory to construct a dynamic url so that 'greet' is called with a newTime arg.
How can I modify poller.get() to pass in 'newTime'?
poller1 = poller.get(greet, {action: 'jsonp_get', delay: 1000});
.factory('greet', function ($resource) {
return $resource('https://www.example.com?time=' + newTime,
{
},
{
jsonp_get: { method: 'JSONP' }
});
})
/-- Demo --/
angular.module('myApp', ['ngResource', 'emguo.poller'])
.factory('greet1', function ($resource) {
return $resource('https://angularjs.org/greet.php',
{
callback: 'JSON_CALLBACK',
name: 'Emma'
},
{
jsonp_get: { method: 'JSONP' }
});
})
.factory('greet2', function ($resource) {
return $resource('https://angularjs.org/greet.php',
{
callback: 'JSON_CALLBACK',
name: 'You'
},
{
jsonp_get: { method: 'JSONP' }
});
})
.controller('myController', function ($scope, poller, greet1, greet2) {
var poller1, poller2;
/*-- Automatically start poller1 on page load --*/
poller1 = poller.get(greet1, {action: 'jsonp_get', delay: 1000});
poller1.promise.then(null, null, function (data) {
$scope.data1 = data;
});
/*-- Actions --*/
$scope.stop = function () {
poller1.stop();
};
$scope.restart = function () {
poller1 = poller.get(greet1);
};
$scope.faster = function () {
poller1 = poller.get(greet1, {delay: 300});
};
$scope.slower = function () {
poller1 = poller.get(greet1, {delay: 1500});
};
$scope.startPoller2 = function () {
poller2 = poller.get(greet2, {action: 'jsonp_get', delay: 1000});
poller2.promise.then(null, null, function (data) {
$scope.data2 = data;
});
};
$scope.stopBoth = function () {
poller.stopAll();
};
$scope.restartBoth = function () {
poller.restartAll();
};
});
Didn't use angular-poller, but seems you should be able to get what you want with the property argumentsArray
:
var poller1 = poller.get(greet, {
action: 'jsonp_get',
delay: 1000,
argumentsArray: [{
time: newTime
}]
});
The array argumentsArray
, therefore the time, is evaluated when the poller is retrieved.
Edit: After clarification, it appears you need to vary a parameter for each tick of the polling, and not when you get the poller. You could solve that by adding the parameter in a request interceptor:
// define interceptor
app.factory('requestInterceptor', function() {
return {
'request': function(request) {
// if needed, wrap the following in a condition
request.params = request.params || {};
request.params.time = moment();
return request;
}
}
})
// register interceptor
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('requestInterceptor');
})