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?

-提前感谢您的浏览。

您对 $timeout 的用法是正确的。您对服务的定义不是。

尝试返回一个对象,您在其中定义了 doWork 方法。像这样定义服务:

angular.module( 'myApp' ).factory( 'myService', myService);

function myService() {
    var doWork = function() {
         ...
    };
    return { doWork: doWork };
}

您正在从您的服务中返回一个承诺。您不执行以下操作的任何特定原因?

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);

看来你在不必要地散布你的逻辑。