Currently, I am engaged in building an Angular front-end application, aiming to keep things simple without relying on tools like breeze or restangular while still maintaining code integrity. However, I have noticed that my code tends to become overly complex even with just a few lines written.
The main goal is to store user information in a cookie and retrieve it when someone logs in.
The Auth service implementation
var userResource = $resource('/users/:id'); var currentUser = $cookieStore.get("user") || {}; return { currentUser: currentUser, login: function(userId, type, callback) { var self = this; return userResource.save({id: userId}, {}, function(response) { response.then(function(result) { self.currentUser = result.data; $cookieStore.put("user", self.currentUser); if(callback) { callback(self.currentUser); } }); }); }, users: function() { return userResource.query(); } };
The AuthCtrl controller setup
$scope.login = function(userId, type) { Auth.login(userId, type, function(result) { $scope.user = result; }); }; Auth.login("someuser", 'basic', function(result) { $scope.user = result; }); $scope.users = Auth.users();
In another controller:
$scope.user = Auth.currentUser; Snippets.query({user: $scope.user.id}, function(snippets) { $scope.snippets = snippets; });
I have chosen to resolve the promise within the service to save the currentUser and store it in the cookieStore (although its availability on mobile devices may be limited).
However, this approach results in returning the resource instead of the promise, which necessitates passing a callback in all login calls.
Can you suggest a more efficient solution?