Where to initialize data in an Angular service?

I find my way with my first Angular application, and one of the services (used to generate SQL query strings) must be initialized with the schema declared in the block constant. At the moment, the scheme / configuration is not completed, so I do a little processing, and the result then becomes available for the private variable inside the service.

I would like to consult a little with best practice at the same time. There seem to be 3 options.

1) Open a public function initin the factory and call it from another place

This is an opportunity, but I do not want to start the factory from another place (this will be the first thing that loads).

2) Use IIFE in the factory body

It may be smelly, but it’s actually normal.

angular.module('dataService', [])

.constant('DB_CONFIG', {
  // ...data used to bootstrap the service
})

.factory('sqlQueries', 
  ['DB_CONFIG',
  function(){

    var privateStuff_;

    (function(){
       // do processing work on DB_CONFIG in here
       privateStuff_ = result;
    })();

    return {
      // no init function needed!
      publicMethod1: publicMethod1
    }
  }
])

3) Use the block run

Angular run, . , , , factory ? . , .

- ?

+4
1

- . 5 :

  • Factory
  • Provider
  • Constant

, , "".

:

var app = angular.module('app', []);
app.provider('dataService', function() {
    var privateStuff_;
    this.init = function(db_config) {
         // do processing work on DB_CONFIG in here
         privateStuff_ = result;
    }
    function publicMethod1() {
        ...
    }
    this.$get = function() {
       return {
           publicMethod1: publicMethod1
       }
    }
});

DB_CONFIG ( ):

app.constant('DB_CONFIG', {
    ...
});

DB_CONFIG:

app.config(function(dataServiceProvider, DB_CONFIG) {
     dataServiceProvider.init(DB_CONFIG);
});
+4

All Articles