I'm want to use data stored in one service in another service.
Problem: The callback function for data retrieval seems to be async, and I can't apply my methods for the retrieved data.
What data retrieval looks like
app.factory('userService', ['$http', 'rootUserService', function ($http, rootUserService) {
var user = null;
var rootUser;
return {
getUser : function(userId) {
var that = this;
rootUserService.getUser().then(function(data) {
that.rootUser = data;
console.log(data) // working
});
console.log(that.rootUser) // undefined
console.log(rootUser) // undefined
// Do some stuff with rootuser (another async call & compare users)
}
}
}]);
Where data is retrieved from:
app.factory('rootUserService', ['$http', '$rootScope', function($http, $rootScope) {
var user = null;
return {
makeRequest: function(url) {
var that = this;
return $http.get(url).then(function (res) {
return res.data;
});
},
// This is what is used for retrieval
getUser: function() {
if(!this.user) { this.user = this.makeRequest('/api/user/get'); };
return this.user;
}
}
}]);