2016-01-06 142 views
0

我有一个拦截器:AngularJS AJAX状态代码错误处理

angular.module('mobileDashboardApp') 
    .factory('HTTPInterceptor', function ($rootScope, $q, HTTPErrors) { 
     return { 
      responseError: function (response) { 
       $rootScope.$broadcast({ 
        500: HTTPErrors.serverError, 
        503: HTTPErrors.serviceError 
       }[response.status], response); 
       return $q.reject(response); 
      } 
     }; 
    }) 

而且常量定义如下:

angular.module('mobileDashboardApp') 
    .constant('HTTPErrors', { 
     serverError: 'internal-server-error', 
     serviceError: 'service-error' 
    }) 

我如何运行$ rootScope $上做一个控制台。记录每当有500错误?

在我的配置我添加使用拦截器:

.config(function ($httpProvider, $routeProvider) { 
    $httpProvider.interceptors.push([ 
     '$injector', 
     function ($injector) { 
      return $injector.get('HTTPInterceptor'); 
     } 
    ]); 

回答

0

据我所知,你是广播上500个状态和503个状态HTTPErrors.serviceError串事件的HTTPErrors.serverError串事件。所以,你可以通过让在任何一个控制器,你要订阅此代码对这些事件

$rootScope.$on(HTTPErrors.serverError, function(event, args){ 
    console.log("500"); 
}); 
$rootScope.$on(HTTPErrors.serviceError, function(event, args){ 
    console.log("503"); 
}); 
当然

你需要注入HTTPErrors成控制器赶上他们。