2014-12-03 111 views
0

为什么角度$资源没有请求和请求错误拦截器?Ang ng ngResources请求拦截器

Theres any way to do that?

文档内容:

拦截 - {对象=} - 拦截器对象具有两个可选的方法 - 响应和responseError。使用http响应对象调用response和responseError拦截器。请参阅$ http拦截器。

回答

1

您可以按如下方式实施自己的拦截器。

app.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('myInterceptor'); 
}); 

app.factory('myInterceptor', ['$q', function ($q) { 
    return { 
     request: function (config) { 
      config.headers = config.headers || {}; 
      // insert code to populate your request header for instance 
      return config; 
     }, 
     response: function (response) { 
      if (response.status === 403 || response.status === 401) { 
       // insert code to redirect to custom unauthorized page 
      } 
      return response || $q.when(response); 
     } 
    }; 
}]); 

我希望这会帮助你。

+0

但是这只适用于使用$ http做的Http请求 – 2014-12-03 20:18:04

+2

不,这也适用于$资源。 $ resource包装$ http以用于RESTful Web API场景。 – 2014-12-03 20:21:49

+0

我会试试... – 2014-12-03 20:38:10