I try to create a service for my user. I use a request http for get the current user. For avoid to call my server each time that I call the userService.getCurrentUser() I tried to send a variable if the request has already be send or call the server if it is the first time.
Here my service :
angular.module('UserService', [])
.factory('UserService', function($q , $http, $rootScope,$timeout) {
var currentUser = null;
return {
getCurrentUser: function() {
if (currentUser == null){
var config = {};
config.cache = true;
config.method = "GET";
config.url = "users/get_current_user";
return $http(config)
.then(function(response) {
if (typeof response.data === 'object') {
currentUser = response.data.user;
return response.data.user;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
else{
return currentUser;
}
}
};
});
Unfortunately I call my request few time because the promise is not immediately resolved. How can I fix this to be sure to call my server once.
And how call this function from my controller because some time the return value is an promise so I use .then() and sometime it will be the value currentUser.