如果用户未登录,我正在尝试干净地实现一种将用户重定向到登录路由的方法。我的解决方案基于此处的另一个 SO 答案,该答案不能开箱即用。这是我的解决方案。
angular.module('myApp', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
var requireAuthentication = function () {
return {
load: function ($q) {
console.log('Can user access route?');
if (g_isloggedIn === true) { // fire $routeChangeSuccess
var deferred = $q.defer();
deferred.resolve();
console.log('Yes they can!');
return deferred.promise;
} else { // fire $routeChangeError
console.log('No they cant!');
return $q.reject("'/login'");
}
}
};
};
$routeProvider
.when('/some_page_that_requires_authentication', {
templateUrl: '/views/secret.html',
controller: 'secretCtrl',
resolve: requireAuthentication()
})
.when('/anybody_can_see_me', {
templateUrl: '/views/public.html',
controller: 'publicCtrl',
});
}]);
我的问题是,我在哪里可以监听$routeChangeError
事件以便重定向路由?我尝试在指令中执行此操作,但永远无法触发事件。我不能将它放入控制器中,因为如果承诺被拒绝,它将不会加载。有什么想法吗?