Last active
October 18, 2015 00:28
-
-
Save martynchamberlin/4ef46a0aa0d2f3559d78 to your computer and use it in GitHub Desktop.
Simple way to cache the information about the logged in user, using an AngularJS service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** This file serves as a usage example **/ | |
angular.module("MyApp").controller("homeCtrl", ["$scope", "$rootScope", "UserService", homeCtrl]); | |
function homeCtrl($scope, $rootScope, UserService) { | |
UserService.GetUser().then(function(user) { | |
console.log( user.FirstName ); | |
}, function() { | |
console.log( 'An error occurred' ); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module("MyApp") | |
.factory("UserService", ["$http", "$rootScope", "$q", UserService]); | |
function UserService($http, $rootScope, $q, API_URL) { | |
return { | |
//Function returns a promise either way, | |
// so calling functions have no idea if we're calling the database or not. | |
// This allows for handy caching. | |
var loadingUser = false; | |
GetUser: function() { | |
if (!$auth.isAuthenticated()) { | |
deferred.reject("User is not signed in."); | |
} | |
else if ($rootScope.user) { | |
deferred.resolve( | |
$rootScope.user); | |
} else if (loadingUser) { | |
return deferred.promise; | |
} else { | |
loadingUser = true; | |
$http.get(API_URL + "users/0").then(function(user) { | |
$rootScope.user = user.data; | |
loadingUser = false; | |
deferred.resolve($rootScope.user); | |
}, function(error) { | |
// Very important that we release the resource! | |
loadingUser = false; | |
deferred.reject(error.data); | |
}); | |
} | |
return deferred.promise; | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment