AngularJS: Background process

Problem

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?

Problem courtesy of: pixelfreak

Solution

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
})
Solution courtesy of: maurycy

Discussion

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 :<
    }
});
Discussion courtesy of: Medet Tleukabiluly

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

Discussion courtesy of: Robbert Draaisma

This recipe can be found in it's original form on Stack Over Flow.