问题
I have this service
which checks if there a new data from the back end. It it working fine.But the problem is I cant get the data from the service to the controller using $watch
nor using the promise
.
SERVICE
.service('notificationPollService',function($q, $http, $timeout){
var notification={};
notification.poller = function(){
return $http.get('some/routes/')
.then(function(response) {
$timeout(notification.poller, 1000);
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
$timeout(notification.poller, 5000);
return $q.reject(response.data);
});
}
notification.poller();
return notification;
})
WATCH IN THE CONTROLLER
$scope.$watch('notificationPollService.poller()', function(newVal){
console.log('NEW NOT', response) // does nothing either.
}, true);
PROMISE IN THE CONTROLLER
notificationPollService.poller().then(function(response){
console.log("NEW NOTI", response) // not logging every poll success.
});
Is there a way that I missed on how to solve this? Or am I just doing something wrong?
回答1:
Probably using promise in this case is not the most convenient approach because it is not supposed to be resolved multiple times. You can try to implement poller with old plain callbacks, you can call them repeatedly without need to create new instance of the promise:
.service('notificationPollService', function ($q, $http, $timeout) {
var notification = {};
notification.poller = function (callback, error) {
return $http.get('some/routes/').then(function (response) {
if (typeof response.data === 'object') {
callback(response.data);
} else {
error(response.data);
}
$timeout(function(){
notification.poller(callback, error);
}, 1000);
});
};
return notification;
});
notificationPollService.poller(function(data) {
$scope.data = data; // new data
}, function(error) {
console.log('Error:', error);
});
来源:https://stackoverflow.com/questions/32412070/angularjs-how-to-get-data-from-a-polling-service-to-a-controller