Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 326
jtfairbank Avatar asked Apr 03 '13 20:04

jtfairbank


People also ask

How do I inject a module in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.

How define module in AngularJS?

var app = angular. module("myApp", []); The [] parameter in the module definition can be used to define dependent modules.

How custom services are used in AngularJS?

Services are normally injected using dependency injection mechanism of AngularJs. Actually angular js provides many inbuilt services for our uses, eg. $http, $route, $location etc. Each service is responsible for a specific work as example , $http is used for make ajax request call to get or post the server data.


1 Answers

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

like image 118
Josh David Miller Avatar answered Sep 30 '22 06:09

Josh David Miller