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 controllers or states until logout?
Now I'm resolving many times in many states or controllers currentUser()
, I found in docs: authparseresponse that it is possibility to make own service, but I don't know how to handle this in right way.
e.g in ui-router I've two server calls, would be sufficient only when page is loaded:
.state('login', {
url: '/login',
templateUrl: 'auth/_login.html',
controller: 'AuthCtrl',
onEnter: [
'$state', 'Auth',
function($state, Auth) {
Auth.currentUser().then(function() {
$state.go('home');
});
}
]
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
onEnter: [
'$state', 'Auth',
function($state, Auth) {
Auth.currentUser().then(function(user) {}, function(err) {
$state.go('home');// user not logged in
});
}
]
})
or each time next server call in NavController:
app.controller('NavController', [
'$state', '$scope', 'Auth', function($state, $scope, Auth) {
$scope.signedIn = Auth.isAuthenticated;
$scope.logout = Auth.logout; // logout function
Auth.currentUser().then(function(user) {
$scope.user = user;
});
$scope.$on('devise:login', function(e, user) {
$scope.user = user;
});
$scope.$on('devise:logout', function(e, user) {
$scope.user = {};
$state.go("home");
});
}
]);
I found similar question without answer: stackoverflow