简体   繁体   中英

How to organize some Utils files in AngularJS to call from app.config?

I need to configure AngularJS - set default $http headers. In my case i need to generate some of them. To make this i need to call some reusable function from Utils service.

As app.config doesn't support services injection how can i organize my code to enable this injection?

app.service('Utils', function(){
    this.generateGuid(){}
});

app.config(['Utils', function(Utils){
    //...
}]);

Or should i create my own custom js files with raw functions?

If the Utils service doesn't require any other services, you could write it as a provider like this:

app.provider('Utils', function () {
  this.generateGuid = function () {};

  this.$get = function () {
    return this; // a provider instance and service instance will be the same object.
  };
});

then inject a provider instance in app.config:

app.config(function (UtilsProvider) {
    UtilsProvider.generateGuid();
});

to use in app.run() or controllers, just inject a service instance as usual:

app.controller('FooController', function (Utils) {
    Utils.generateGuid();
});

Hope this helps.

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