Hav3n
Hav3n

Reputation: 393

Use constant from another module in current module's service

I would like to store all my constants in one place, and inject this module everywhere I need it.

constant.js

(function(){

        var constantModule = angular.module('Constants',[]);
        constantModule.constant('AppDefaults',{
            DEFAULT_PAGE_SIZE : 100
        });

    }());

and use this constant in another module here:

     var app = angular.module('app',['Constants']);
     app.controller('AppController',function($scope,AppService){

     $scope.someMethod = function() {
       var response = AppService.doSomething();
     }

    });
    app.service('AppService',['$http', '$q','Constants',function($http,$q,Constants){

  return({
   doSomething:doSomething
  });

function doSomething() {
  method: "post",
        url: "/foo/bar",
        data: {
         pageSize: Constants.AppDefaults.DEFAULT_PAGE_SIZE
        }
}
}]);

But I angular cannot inject Constants into the service. Is there a way around this ?

Upvotes: 0

Views: 1364

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

A module can't be injected. A constant can, however, just as a service:

app.service('AppService',['$http', '$q', 'AppDefaults', function($http, $q, AppDefaults) {

    return({
        doSomething:doSomething
    });

    function doSomething() {
        return $http({
            method: "post",
            url: "/foo/bar",
            data: {
                pageSize: AppDefaults.DEFAULT_PAGE_SIZE
            }
        });
    }
}]);

Upvotes: 1

Related Questions