AngularJs如何从一个轮询业务数据控制器控制器、业务、数据、AngularJs

2023-09-13 05:18:51 作者:一见你就笑

我有这样的服务它检查是否从后端有一个新的数据。据它的工作fine.But问题是我不能使用从服务到控制器获取数据 $观看也不使用

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('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在控制器

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

PROMISE在控制​​器

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?

推荐答案

在这种情况下可能使用的承诺是不是最方便的方法,因为它是不应该被解析多次。你可以尝试实现轮询老平原回调,可以反复调用它们,而不需要创建承诺新实例:

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(notification.poller, 1000);
        });
    }

    notification.poller();

    return notification;
});

notificationPollService.poller(function(data) {
    $scope.data = data; // new data
}, function(error) {
    console.log('Error:', error);
});