AngularJs如何从一个轮询业务数据控制器 [英] AngularJs how to get data from a polling service to a controller

查看:810
本文介绍了AngularJs如何从一个轮询业务数据控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的服务它检查是否从后端有一个新的数据。据它的工作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);
});

这篇关于AngularJs如何从一个轮询业务数据控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆