2016-02-12 75 views
1

我正在使用angularjs和Im试图用拦截器处理错误。AngularJS - 未授权和拦截器

我所遇到的是如何处理不同的错误会议的问题过期登录失败当服务器回复都与401

似乎拦截配置之前,将执行定义任何其他拦截器(顺序定义事项):

var configInterceptor = function($httpProvider) 
    { 
    $httpProvider.interceptors.push('unauthorizedInterceptor'); 
    }; 

angular.module('app', []) 
     .config(configInterceptor) 
     .controller.... 

拦截在$资源中定义的s仅在它们通过configInterceptor后才会被视为

var res = $resource(serviceUrl + '/users/login',{},{ 
      post:{ 
       method:'POST', 
       params: {}, 
       withCredentials: true, 
       interceptor: { 
        responseError: function(){ 
        console.log('login interceptor'); 
        } 
       } 
      } 
     }); 

我想有一个单点控制,当会话已过期(推送用户登录页面和发送相应的消息),而无需到unauthorizedInterceptor添加到所有$资源,一个一个。

如果错误是由于用户试图登录并失败,那么拦截器应该以不同的方式对待它(消息将不同)。

任何方式来正确解决这个问题?我也试着定义拦截器只适用于特定的模块,但它们被触发。

+0

所有拦截器将被触发。你可以在你的拦截器中检查url,如果它匹配登录路径,那么做你的处理,否则跳过它,类似地创建一个拦截器的认证失败处理和有条件地执行工作 –

+0

因为我们使用的角度,有一个会话服务,告诉我什么时候用户已连接。检查用户会话是否设置有助于我有条件地处理拦截。你说的相同的解决方案,而不是检查URL我检查会话对象。无论如何,谢谢。 – kitimenpolku

+0

这是一个有状态的解决方案,您应该检查用户打开新选项卡时会发生什么。这应该触发“会话过期”而不是登录失败(IMO)。无论如何,如果你的服务器只返回401没有消息,这将不可能知道正确的方式来处理这个问题。有消息吗?您可以检查'''''''''''''''''''''''''''''''你在' – martinczerwi

回答

0

我会做这样的事情:

angular.module('app', []).factory('unauthorizedInterceptor', unauthorizedInterceptor); 

function unauthorizedInterceptor($q, ngUserAuthService) { 

    return { 
     'responseError': function (response) { 

      if (response.status === 401) { 
       // find out if the session has expired or the user login has failed 
       if (sessionExpired()) { 
        doRedirectToSomewhere(); 
       } else if (loginHasFailed()) { 
        response.loginFailed = true; // use this later 
       } 
      } 
      return $q.reject(response); 
     } 
    }; 
} 

然后当你要检查失败的登录拦截仅添加到$资源:

var res = $resource(serviceUrl + '/users/login',{},{ 
    post:{ 
     method:'POST', 
     params: {}, 
     withCredentials: true, 
     interceptor: { 
      responseError: function(response) { 
       console.log('login interceptor'); 
       console.log('The login has failed: ' + response.loginFailed); 
      } 
     } 
    } 
}); 
+0

我就是这么做的。谢谢 – kitimenpolku