How to create own service accessible globally that will call server by currentUser()
only once on page load, if User is logged in then keep it and provide data to c
As we know factory is a singleton object and basically it is used for data sharing. We can inject it to any controller and functions as an dependency .So this may be also solve your problem. inject this service to your state resolve block and check if user exists or not if not then call the fetch user function of factory
app.factory("User", function($http, $q, $rootScope) {
var user = null;
return {
fetchUser: function() {
/*your ajax call that return current user*/
user = YOUR_SERVER_RESPONSE;
return user;
},
getUser : function(){
return user;
},
setUser : function(u){
user = u;
}
}
});
and your state config block is look like
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
resolve : function(User){
if(User.getUser()){
return User.getUser();
}else{
return User.fetchUser();
}
}
})