我正在尝试创建类似于 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;
});
我尝试在我的 Controller 中使用它,如下所示:
Poller.poll(
function(jsonAPI) {
console.log(jsonAPI);
},
function(error) {
console.log('Error:', error);
}
);
数据已正确获取,但似乎存在两个问题。
- 回调函数仅被调用一次,并且不根据$timeout。我在服务中添加了回调结束错误的条件,因为如果没有它们,它会抛出错误
callback is not a function
。当我刷新或更改 View 时,回调函数将再次被调用。 - $timeout 似乎每 10 秒触发两次,而不是一次。
最佳答案
使用
$timeout(function () {
notification.poll(callback, error);
}, 10000);
而不是
$timeout(notification.poll, 10000);
关于javascript - 回调函数在 Service 中使用 $timeout 不会只调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35734285/