问题
I'm using angular-acl (https://github.com/mikemclin/angular-acl) to manage the authorization logic of my application and It's working fine, except when the user open a new window/tab.
When the user open a new window/tab I cannot access the sessionStorage so I need to reload the acl and the user roles from the API, but as the request is asynchronous it normally resolves after the check for permission.
How can I certify that the stateProvider only will change the page after the acl list is loaded?
Here is how I'm trying to reload the permission:
myApp.run(['AclService', 'Auth', '$http', function (AclService, Auth, $http) {
if(!AclService.resume()) {
Auth.load_acl();
Auth.load_user_roles();
// I need to certify that these requests are complete before continue
}
}]);
The service that make the request:
var authServices = angular.module('authServices', []);
authServices.factory('Auth', ['$http', 'AclService', function($http, AclService) {
var authService = {};
authService.load_acl = function() {
return $http.get('/auth/get_acl').then(function(response){
var aclData = {};
for(i in response.data) {
var role = response.data[i];
if(aclData[role.name] === undefined)
aclData[role.name] = [];
aclData[role.name].push(role.ability_name);
}
AclService.setAbilities(aclData);
});
};
authService.load_user_roles = function() {
return $http.get('/auth/get_user_roles').then(function(response){
for(role in response.data) {
AclService.attachRole(response.data[role]);
}
});
};
return authService;
}])
回答1:
Use state/route resolver:
...
resolve: {
auth: function (AclService, Auth, $q) {
if(!AclService.resume()) {
return $q.all([Auth.load_acl(), Auth.load_user_roles());
}
}
}
Wrap it into separate service if you need to reuse it.
来源:https://stackoverflow.com/questions/31644412/how-to-load-session-data-before-stateprovider-state-changes-in-angularjs