【问题标题】:AngularJs how to get data from a polling service to a controllerAngularJs如何从轮询服务获取数据到控制器
【发布时间】:2015-09-05 10:35:54
【问题描述】:

我有这个service,它检查后端是否有新数据。它工作正常。但问题是我无法使用$watchpromise 将数据从服务获取到控制器。

服务

.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.
});

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

【问题讨论】:

    标签: javascript angularjs long-polling watch


    【解决方案1】:

    在这种情况下使用 promise 可能不是最方便的方法,因为它不应该被多次解析。您可以尝试使用旧的普通回调实现 poller,您可以重复调用它们而无需创建新的 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);
    });
    

    【讨论】:

    • 你是巫师吗?谢谢;)
    • 我收到错误“回调不是函数”,我该如何解决?
    • 传递回调函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2015-02-28
    • 2015-11-15
    相关资源
    最近更新 更多