【发布时间】:2016-03-01 21:52:26
【问题描述】:
我正在尝试创建类似于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);
}
);
数据被正确提取,但似乎有两个问题。
- 回调函数只被调用一次,而不是根据 $timeout。我在服务中添加了回调结束错误的条件,因为没有它们会引发错误
callback is not a function。当我刷新或更改视图时,再次调用回调函数。 - $timeout 似乎每 10 秒触发两次,而不是一次。
【问题讨论】:
-
为什么不带参数调用notification.poll()?
-
参数不是我放的两个函数吗?顺便说一句,你的答案很完美。
标签: javascript angularjs callback