请求拦截器是否可以在angularJS中创建http响应

请求拦截器是否可以在angularJS中创建http响应

问题描述:

我正在创建应用程序中的离线模式。无论何时发送一个http请求,我都希望拦截器检测网络状态。如果状态没有连通性,我想创建一个模拟响应,让它感觉好像响应来自服务器。请求拦截器是否可以在angularJS中创建http响应

你可以检查您是否在线或者通过阅读在你的拦截器的响应的状态,如果其501分之401的/ etc:

var interceptor = ['$rootScope', '$q', function ($rootScope, $q) { 
    function success(response) { 
     return response; 
    } 
    function error(response) { 
     var status = response.status; // error code 
     if ((status >= 400) && (status < 500)) { 
     $rootScope.broadcast("AuthError", status); 
     return; 
     } 
     if ((status >= 500) && (status < 600)) { 
     $rootScope.broadcast("ServerError", status); 
     return; 
     } 
     // otherwise 
     return $q.reject(response); 
    } 
    return function (promise) { 
     return promise.then(success, error); 
    } 
}] 

还有另外一种方式,使用HTML5,但我猜在某些浏览器上不起作用。这是使用navigator.onLine属性来实现,如:

if (navigator.onLine) { 
    //I'm online 
} else { 
    I'm not online 
} 

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

如果你把你的请求拦截器内的对象,这将触发对responseError拦截通话,传递扔对象作为其论据。

你必须找到一个方法通知responseError拦截器,这不是一个真正的错误,它应该返回一个自定义的响应。

的responseError拦截器可以选择恢复错误返回响应对象o失败返回拒绝承诺(查看角的$ HTTP拦截文档)

编辑:如果您的请求Interceptor抛出一个对象,你不能避免控制台中的错误消息。最好是返回一个被拒绝的promise传递配置对象作为值,并在其中放置额外的信息,以便responseError检测特殊情况。