AngularJs 如何从轮询服务获取数据到控制器

2024-01-14

我有这个service它检查后端是否有新数据。它工作正常。但问题是我无法使用从服务到控制器的数据$watch也不使用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;
})

在控制器中观看

$scope.$watch('notificationPollService.poller()', function(newVal){
    console.log('NEW NOT', response) // does nothing either.
}, true);

控制器的承诺

notificationPollService.poller().then(function(response){
    console.log("NEW NOTI", response) // not logging every poll success.
});

有没有我错过的解决这个问题的方法?或者我只是做错了什么?


在这种情况下使用 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);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJs 如何从轮询服务获取数据到控制器 的相关文章