I'm developing an AngularJS application.
I try to write a service method that can periodically auto reload some content from HTTP request and notify the controller that called the method.
So I search to use the promse API of AngularJS and I use the $timeout service, but I can't return the promise while the method is running not asynchronously...
So here, the promise is never returned, and I understand why, but I don't know what is the correct pattern to do what I want.
angular.module('myModule')
.factory('myService', [
'$timeout',
'$q',
'$doMyHttpRequest',
function($timeout, $q, $doMyHttpRequest){
var d = $q.defer();
return function(){
autoRefresh = function(){
$timeout(function(){
$doMyHttpRequest(function(){
d.notify({ // notify the update success
updated: true
});
},function(){
d.notify({ // notify the update error
updated: false
});
});
this.autoRefresh(); // refresh again in 60 seconds
},60000);
};
this.autoRefresh();
return d.promise;
}
}])
.controller('myCtrl', ['myService', function(myService){
myService().autoRefresh().then(function(){ // never reached because promise is never returned
// do my stuff when succeed
},function(){ // never reached because promise is never returned
// do my stuff when error
});
}])
;
d.resolve()/d.reject()instead ofd.notify()returnstatement is never reached in the function. Then, resolve(), reject() or notify() is not the point.autoReloadObservations()? notice too thatautoRefreshis never called in ur example