biagidp
biagidp

Reputation: 2185

Application wide constants in Angularjs

We have an API that requires an application id be included with every request. I'd like for this id to be accessible in every controller and I'd ideally like to only set it once. I can set it at the top level by doing:

angular.module('applicationName', 
['controller1', 'controller2', 'controller3'])
.constant('APPLICATION_ID', '12345abcde');

But I'd like to be able to access it in controller1/2/3. What's the best way to set the APPLICATION_ID variable so it's available in all components of the application?

Upvotes: 0

Views: 569

Answers (2)

SaoBiz
SaoBiz

Reputation: 1249

Since you need to send the Application_ID with every request to your api, as mentioned in the comments, you can modify the $http service to add the ID.

Define the constant

angular.module('myModule')
  .constant('APPLICATION_ID', 'foobarbaz');

Inject the constant into your $http service to send with every request.

angular
  .module('myModule')
  .config(httpConfig);

httpConfig.$inject = ['$httpProvider', '$provide'];

function httpConfig($httpProvider, $provide) {
  $provide.factory('httpInterceptor', ['APPLICATION_ID', function (APPLICATION_ID) {
    return {
      request: function (config) {
        // APPLICATION_ID can now be used in all your requests
        // Example:
        // To URL: GET /api/v1/users?appid=foobarbaz
        if (config.mehtod === 'GET') {
          var sep = config.url.indexOf('?') === -1 ? '?' : '&';
          config.url = config.url + sep + 'appid=' + APPLICATION_ID;
        }

        return config;
      }
    };
  }]);
}

$httpProvider.interceptors.push('httpInterceptor');

Now you can use the Application_ID in all of your requests without the need to inject it into all of your controllers.


Resources

https://docs.angularjs.org/api/ng/service/$http

  • See section 'Setting HTTP Headers' on how to modify the headers sent
  • See section 'Interceptors' for a more detailed example than the one above

Upvotes: 0

Scott
Scott

Reputation: 1690

      angular.module('applicationName', 
         ['controller1', 'controller2', 'controller3'])
         .constant('APPLICATION_ID', '12345abcde');

And then in your controller

      application.controller('myController', 
                        ['$scope','APPLICATION_ID',function($scope,applicationId)               
      {

         console.log("app id="+applicationId);

      }]);

Upvotes: 2

Related Questions