操作方法:AngularJS服务或其他组件在模块加载时即时运行?

时间:2015-08-28 19:04:02

标签: javascript angularjs web-services web-frontend

您好读者,Angularistics,

我想知道创建服务的配方,或提供者或任何其他角度组件,它们在模块加载时立即实例化ONCE。

E.g。我有一个名为'utils'的模块 我有一个名为'myApp'的应用模块,它依赖于'utils'

我在utils模块中有一个名为'intervalRegister'的服务,它包含一个用于app-wide api轮询的注册方法。

每当我们想要注册轮询时,我们必须使用此服务,但是当窗口失去焦点时,此服务会巧妙地停止所有轮询 - 以避免不必要的网络流量。

目前这个'intervalRegister'是通过'utils'模块的run方法实例化的,但我不认为它是最好的解决方案。

1 个答案:

答案 0 :(得分:0)

我认为将其添加到run方法是可以的,但作为替代方案,您可以添加使用interval服务的控制器。

这可能更好,因为您还可以将轮询相关逻辑添加到该控制器中。

我不知道任何其他方式自动启动间隔,我还没有在谷歌中看到过。

请查看下面的演示或此jsfiddle

angular.module('demoApp', ['utils'])
	.controller('pollController', PollController)
	.controller('mainController', MainController);

angular.module('utils', [])
    //.run(['intervalTimer', function(intervalTimer){}])
	.service('intervalTimer', IntervalTimer)
	

function IntervalTimer($interval, $log) {
    var self = this;
    this.count = 0;
    this.pollCallbacks = [];

    this.addPoll = function(callback, scope) {
        return self.pollCallbacks.push({
            fn: callback,
            scope: scope
        });
    };

    this.timer = function() {
        self.count++;
        $log.log('hello from interval timer', self.count);
        if (self.pollCallbacks.length > 0 ){
            angular.forEach(self.pollCallbacks, function(callbackObj) {
                //console.log(callbackObj.scope);
                callbackObj.fn.call(callbackObj.scope);
            });
        }
    };
    $interval(this.timer, 1000);
}

function MainController() {
	
}

function PollController(intervalTimer, $log) {
    var vm = this;
    this.messages = '';
    this.pollCounter = 0;
    this.addPolling = function() {
        var callbackObj = {
            pollCounter: angular.copy(vm.pollCounter++),
            fn: function() {
                var msg = 'poll callback no. ' + this.pollCounter + ' called!' 
    			$log.log('poll callback no. ' + this.pollCounter + ' called!');
                vm.messages += 'poll callback no. ' 
                    + this.pollCounter + ' called!' + '\r\n';
   			}
        };
        
    	vm.pollCounter = intervalTimer.addPoll(callbackObj.fn, callbackObj);
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as mainCtrl">
    <div ng-controller="pollController as pollCtrl">
        <button ng-click="pollCtrl.addPolling()">add poll</button>active polls: {{pollCtrl.pollCounter}} <pre ng-bind="pollCtrl.messages"></pre>

    </div>
</div>