Angularjs $interval:使用回调函数作为传入函数的参数
Angularjs $interval: Using a callback function as a param into the pass in function
很抱歉这个标题让人困惑,我真的不知道该如何表达这个问题。我试着用谷歌搜索了很多不同的短语,但同样的结果不断出现,这不是我想要的。
首先,我对angularjs和javascript很陌生,所以如果我错过了一些非常简单的东西,我很抱歉。
查看间隔文档:https://docs.angularjs.org/api/ng/service/美元区间
我想做的是像下面这样调用$interval服务:
controller.js:
(function() {
function controller($scope, $interval, myService) {
var stop;
function handleCallback( myParams ) {
//do stuff with myParams
//call stopInterval function if neccessary.
}
$scope.doSomething = function() {
stop = $interval(myService.doWork, 5000, 0, handleCallback);
};
var stopInterval = function() {
if (angular.isDefined( stop ) ) {
$interval.cancel( stop );
stop = undefined;
};
};
}
angular.module( 'myApp' ).controller( 'controller', controller);
})();
my-service.js
(function() {
function myService($q, $http) {
myService.doWork = function( callback ) {
var dfd = $q.defer();
$http.get('url').success( function( response ) {
//Would parse the response into an appropriate response
//before calling the callback method with it.
callback( response );
dfd.resolve( response );
}).error( function( response ) ) {
//will add an error callback once I get this working
dfd.reject( response );
});
return dfd.promise;
}
return myService
}
angular.module( 'myApp' ).factory( 'myService', myService);
})();
当我执行这个时,我开始点击myService。doWork(callback)方法,回调从来不是一个函数,只是一个数字,每次它被击中,这个数字就加1。
我不确定这个数字是从哪里来的,但我猜我没有正确设置$interval调用。看看angular文档,Pass参数类型是"*",所以我假设它意味着支持任何类型,函数都是有效的参数。事实并非如此吗?是否不可能将函数作为参数传递给$interval服务的fn ?
-提前感谢您看一下
您正在从服务返回一个承诺。有什么特别的原因让你不这么做吗?
var stop = $interval(function () {
myService
.doWork()
.then(function (res) {
//if promise is successful, res is your data
$interval.cancel(stop)
})
.catch(function (err) {
//if promise was rejected, err is your servers error message
});
}, 5000);
似乎你在不必要地分散你的逻辑。
您对$timeout
的使用是正确的。你对服务的定义不是。
尝试返回一个定义doWork方法的对象。这样定义服务:
angular.module( 'myApp' ).factory( 'myService', myService);
function myService() {
var doWork = function() {
...
};
return { doWork: doWork };
}
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数