简体   繁体   中英

AngularJS: Background process

I have an angular app and I would like to add a background process that runs without any view. All it is doing is regularly call a webservice and do something about it, no UI.

A quick and dirty way is to simply put the code in window.onLoad. But should I be thinking of doing this the angular way? If so, do I put the code in a Service? How would I "start" this service initially?

You answered it yourself, service is the right choice, you can inject it in any controller you have on app, if that's not the case and you have no controller (or directive) then you can do it in angular.run

angular.module('lookMaMyModule').run(function(injectables){
  do something fancy on run
})

Here's simple concept for you, it might have small problems, but you will get the idea.

angular.bootstrap2 = function(module, element, callback){
    angular.bootstrap(module, element);
    callback();
}

remove ng-app tag from html, and bootstrap app

If background process is ng module, then use angular.module('name').run(); else use self bootstraping technique

app.js

angular.module('name', ['deps']);
angular.bootstrap2(['name'], document.body, function(){
    var process_1 = new MyServ();
    process_1.start();
});

service.js

var MyServ = function(){
    this.intervalId = 0;
    this.start = function(){
        this.intervalId = setInterval(function(){
            console.log('executing');
        }, 1000);
    }
    this.stop = function(){
        setInterval.cancel(this.intervalId); //don't remember api, sorry :<
    }
});

I think what you're looking for is

app.run()

this gets called when the angular app is starting

see https://docs.angularjs.org/api/ng/type/angular.Module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM