我正在尝试编写一个模拟轮询功能的服务。我的代码如下:
app.service('poller', ['$timeout',
function($timeout) {
return ({
poll
})
function poll(e) {
$timeout(function() {
poll(e);
}, 5000);
}
}
]);
当我将它注入(inject) Controller 时,我尝试像这样使用它:
poller.poll($scope.getNewMessages());
奇怪的是它只被调用一次。另外,当我尝试在服务中使用控制台日志(例如 console.log(e)
)时,我得到了未定义的信息。我做错了什么?
最佳答案
您需要将函数作为值传递给轮询器函数,并且需要调用该函数:
app.service('poller', ['$timeout', function($timeout) {
return ({
poll
});
function poll(e) {
e();
$timeout(function() {
poll(e);
}, 5000);
}
}
]);
poller.poll($scope.getNewMessages);
关于javascript - 创建一个服务来重复 Controller 中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707073/