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?
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.
var app = angular. module("myApp", []); The [] parameter in the module definition can be used to define dependent modules.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With