Reputation: 467
I have several rest services that looks like this
/user/:userId/resource/:resourceId
Most of the time the user wants to get his own resources (although sometimes he wants to get anther user's resource) so I want the default parameter to be the current user Id but I cannot save the UserId on a rootscope/service because if the user refreshes the browser this will be gone, so I want to do something like this:
$resource('/user/:userId/resource/:resourceId', { userId: getUserId, resourceId: '@id' })
the problem is that the getUserId()
returns a promise:
function getUserId() {
if (!$rootScope['user']) {
$rootScope['user'] = UserService.get({ userId: 'current' })
}
return $rootScope['user'].$promise.then(function (user) {
return user.id;
}
}
how can I make it work for all services (as for now I'm just always chaining every resource service after the userId getter... is there a better way?
Upvotes: 0
Views: 65
Reputation: 1486
Use the browser session to store this non-sensitive data.
// Set the user object into the session as a JSON object
function setUser(user) {
sessionStorage.setItem("user", JSON.stringify(user));
}
// Retrieve user object and parse the userID
function getUserId() {
var tmpUser = JSON.parse(sessionStorage.getItem('user'));
return tmpUser.userID;
}
Then your $resource will not have any promises being returned to it and you can access/modify the userID from anywhere in the code without polluting your $rootScope.
Upvotes: 1