使用$ timeout

时间:2016-03-01 21:52:27

标签: javascript angularjs callback

我尝试创建类似于this示例的服务。我的代码如下:

app.service('Poller', function ($q, $http, $timeout) {

var notification = {};
notification.poll = function (callback, error) {
    return $http.get('https://someapi.com').then(function (response) {
        if (typeof response.data === 'object') {
            if (callback){
                callback(response.data);
                console.log('tick');
            }
        } else {
            if (error) {
                error(response.data);
            }
        }
        $timeout(notification.poll, 10000);
    });
}

notification.poll();

return notification;
});

我尝试在我的控制器中使用它:

Poller.poll(
    function(jsonAPI) { 
        console.log(jsonAPI);
    }, 
    function(error) {
        console.log('Error:', error);
    }
);    

正在正确提取数据,但似乎存在两个问题。

  1. 回调函数只调用一次,而不是根据$ timeout。我在服务中为回调结束错误添加了条件,因为没有它们会抛出错误callback is not a function。当我刷新或更改视图时,再次调用回调函数。
  2. $ timeout似乎每10秒触发两次,而不是一次。

1 个答案:

答案 0 :(得分:1)

使用

$timeout(function () {
    notification.poll(callback, error);
}, 10000);

而不是

$timeout(notification.poll, 10000);