Search code examples
angularjsconstantsangular-resource

AngularJS constants in main module


It looks like there's several ways to define constants in Angular.

In this example we are defining two constants in our main module config.js:

  'use strict';
  angular.module('app')
    .constant('URL', 'http://localhost:8080/users')
    .constant('RESOURCES', (function () {
                var resource = 'http://localhost:8080';
                return {
                  USERS: resource + '/users'
                }
              }));
  }());

We have a factory that uses these constants. In the first case, when we want to use the "simple" constant (URL), it works like a charm:

  var app = angular.module('app.user');
  app.factory('User', ['URL', '$resource', function (URL, $resource) {
    return $resource(URL + '/:id', null, {
                       get: {method: 'GET'}
                     });
  }]);

However, when we try to use the main RESOURCES constants, like this:

  var app = angular.module('app.user');
  app.factory('User', ['RESOURCES', '$resource', function (RESOURCES, $resource) {
    return $resource(RESOURCES.USERS + '/:id', null, {
                       get: {method: 'GET'}
                     });
  }]);

We get an undefined error.

Any ideas?


Solution

  • You should have an error with this code, look at the closing of the block

    app.constant('RESOURCES', (function() {
        var resource = 'http://localhost:8080';
        return {
          USERS: resource + '/users'
        }
      })());