我尝试创建类似于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);
}
);
正在正确提取数据,但似乎存在两个问题。
callback is not a function
。当我刷新或更改视图时,再次调用回调函数。答案 0 :(得分:1)
使用
$timeout(function () {
notification.poll(callback, error);
}, 10000);
而不是
$timeout(notification.poll, 10000);