2016-03-20 3 views
0

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

+2

Вы должны были бы использовать 'вернуть deferred.promise', но вы действительно должны полностью [избежать отложенных антипаттерн] (http://stackoverflow.com/ q/23803743/1048572) – Bergi

+0

Большое спасибо .. это была глупая ошибка. Можете ли вы опубликовать это как ответ, чтобы я мог его пометить. – Pavan

ответ

1

Вы забыли .promise, так что вы только вернули отложенную, которая не была ожидаема или значение разрешения, которое вы ожидали.

Но вы должны avoid the deferred antipattern anyway - просто сделать

isAuthenticated(): ng.IPromise<String> { 
    if (this.$rootScope.auth && this.$rootScope.auth.isAuthenticationChecked) { 
     if (this.$rootScope.auth.isAuthenticated) { 
      return this.$q.resolve('OK'); 
//   ^^^^^^^^^^^^^^^^^^^^^^ 
     } else { 
      return this.$q.reject('Unauthorized'); 
//   ^^^^^^^^^^^^^^^^^^^^^^ 
     } 
    } else { 
     return 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; 
       return 'OK'; 
//    ^^^^^^ 
      }, 
      (error: any) => { 
       if (!this.$rootScope.auth) { 
        this.$rootScope.auth = {}; 
       } 
       this.$rootScope.auth.isAuthenticationChecked = true; 
       return this.$q.reject('Unauthorized'); 
//    ^^^^^^^^^^^^^^^^^^^^^ 
      } 
     ); 
    } 
} 
+1

Я думаю, что 'ng.IDeferred ' также должен быть исправлен , – estus

+0

@estus: Да, я забыл, что это машинопись. Вы знаете, будет ли «ng.IPromise » правильным типом? – Bergi

+1

Я часто делаю типизацию, но да, я уверен, что это правильный тип. Кроме того, 'throw' не является взаимозаменяемым с' $ q.reject() 'в $ q. Первый будет также запускать обработчик исключений, я бы сохранил «бросок» для потенциально необработанных ошибок приложения. – estus

Смежные вопросы