以下是我的路由配置角路由解析 - deferred.reject不工作 - 角1 +打字稿
function routes($routeProvider: ng.route.IRouteProvider) {
let accessResolver = ['UserFactory', (UserFactory: any) => {
return UserFactory.isAuthenticated();
}];
//Configuring routes
$routeProvider.when('/', {
templateUrl: '/views/home.html',
controller: 'HomeController',
controllerAs: 'homeCtrl',
resolve: accessResolver
}).when('/login', {
templateUrl: '/views/login.html',
controller: 'LoginController',
controllerAs: 'loginCtrl'
}).otherwise({
redirectTo: '/'
});
}
我的路線更改錯誤處理程序
function run($rootScope: ng.IRootScopeService, $location: ng.ILocationService) {
$rootScope.$on("$routeChangeError",() => {
console.log("Route Change Error");
$location.url('/login?redirect=' + $location.url());
});
}
而且UserFactory
module TheHub {
export interface IUserFactory {
isAuthenticated(): ng.IDeferred<String>;
}
class UserFactory implements IUserFactory {
constructor(private $http: ng.IHttpService, private $q: ng.IQService, private $rootScope: any) {
}
isAuthenticated(): ng.IDeferred<String> {
let deferred = this.$q.defer();
if (this.$rootScope.auth && this.$rootScope.auth.isAuthenticationChecked) {
if (this.$rootScope.auth.isAuthenticated) {
deferred.resolve('OK');
} else {
deferred.reject('Unauthorized');
}
} else {
this.$http.get('secure/user').then(
(response: ng.IHttpPromiseCallbackArg<{}>) => {
if (!this.$rootScope.auth) {
this.$rootScope.auth = {};
}
this.$rootScope.auth.isAuthenticationChecked = true;
this.$rootScope.auth.isAuthenticated = true;
deferred.resolve('OK');
},
(error: any) => {
if (!this.$rootScope.auth) {
this.$rootScope.auth = {};
}
this.$rootScope.auth.isAuthenticationChecked = true;
deferred.reject('Unauthorized');
});
}
return deferred;
}
}
function userFactory($http: ng.IHttpService, $q: ng.IQService, $rootScope: any) {
return new UserFactory($http, $q, $rootScope);
}
userFactory.$inject = ['$http', '$q', '$rootScope'];
angular.module('TheHub').factory('UserFactory', userFactory);
}
這裏的邏輯是,我發射一個請求來檢查用戶是否已經登錄並且有一個會話。 問題是,當用戶尚未登錄時,服務失敗,承諾被拒絕。但是,我不知道爲什麼,處理程序$ routeChangeError沒有被解僱。當出現JavaScript錯誤時它工作正常。
你需要使用'返回deferred.promise',但你真的應該徹底[避免遞延反模式](http://stackoverflow.com/ q/23803743/1048572) – Bergi
非常感謝..這是一個愚蠢的錯誤..你可以發佈這個答案,以便我可以標記它解決.. – Pavan