我有安全服务从服务器获取所有用户权限。以这样的方式调用此服务的最佳位置是应用程序在导航到第一个路由之前等待此承诺得到解决。我将服务定义为提供者,但在配置阶段,我无权访问实际服务的实例,只能访问提供者,所以我不能做像
这样的事情。sercurityService.fetchPermissions.then(function(){
configRoutes();
});
在运行阶段,您可以访问该服务,但在导航到第一条路线之前,如何让应用等待承诺得到解决?
更新
我已经通过解析检查用户是否拥有该路线的权限。但是这个方法hasPermission是异步的。并且工作,以便如果尚未获取权限,则它首先获取它们。我想要做的是在应用程序的早期阶段获取所有权限,以便我可以将hasPermission转换为sync方法。它使编码更容易。以下是我配置路线的方法
getRoutes().forEach(function (r) {
// check if route has a permission defined
// if it has then attach a function to "resolve" property for the route
// since per angluar docs. router will wait for all promises in resolve object to be resolved
// prior to navigating to the route and instantiating controller
// we can use it to check if user has permission, and if not, re-direct user to unauthorized route
var settings = r.config.settings || {};
if (settings.permissions) {
if (!r.config.resolve) {
r.config.resolve = {};
}
r.config.resolve.hasPermission = function ($rootScope, $q) {
var deferred = $q.defer();
securitySvc.hasRoutePermission(settings.name)
.then(function (result) {
if (result === true) {
deferred.resolve(true);
} else {
modalSvc.openEditModal('unauthorized');
deferred.reject();
}
});
return deferred.promise;
};
}
$routeProvider.when(r.url, r.config);
});
答案 0 :(得分:1)
您可以在$routeProvider.when
例如
$routeProvider.when('/permissions', {
templateUrl: 'permissions.html',
controller: 'PermissionController',
resolve: {
resolvedPermissions: ['sercurityService',function(sercurityService) {
return sercurityService.fetchPermissions(); //this will return angular promise object
}]
}
});
内部控制器
angular.controller('PermissionController',['$scope','resolvedPermissions',function($scope,resolvedPermissions){
$scope.permissions = resolvedPermissions; //permissions will get resolved
}]);