Angularjs - how do I set module values in a service?

jtfairbank picture jtfairbank · Apr 3, 2013 · Viewed 12.5k times · Source

I have the following services module for an Angular app.

angular.module('rs.services', [])
  .value('uid', null)

  .factory('login', ['$http', 'uid', function($http, uid) {
    return function(user, pass) {
      var p = $http.post('/login', {"user": user, "pass": pass})
        .success(function(data, status, headers, config) {
          // set uid
        })
        .error(function(data, status, headers, config) {
          // do something
        });

      return p;
    }
  }]);

  // a service that uses uid to authenticate the request
  .factory('userPrefs' ['$http', 'uid', function($http, uid) {
    return function() {
      return $http.post('/user/prefs', {"uid": uid});
    }
  }]);

After a user logs in, the login service returns a unique session id and I want to set the module's uid value for other services calls to refer to.

I'm pretty sure the above code won't work because I can't use a value as a dependency in the module's configuration stage. How can I set the uid value in the login service and access it in other services within the module, or if that's not possible how can I make a value that can be set / get by these services?

Answer

Josh David Miller picture Josh David Miller · Apr 3, 2013

Values that are primitives are not meant to hold information that changes during the course of your application. You need to either have the UID value be an object or a standard service. As an object:

.value( 'uid', {} );

.factory('userPrefs' ['$http', 'uid', function($http, uid) {
  // ...
  uid.id = response.data.uid;
  // ...
});

You might also want to place all your user-related stuff into a single service instead of three. See this other SO post for more info: https://stackoverflow.com/a/14206567/259038