Ниже моя конфигурация маршрутаУгловое разрешение маршрута - 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