angularjs – 在没有服务器请求的情况下拦截$http请求并返回响应
发布时间:2020-12-17 17:02:43 所属栏目:安全 来源:网络整理
导读:我希望,在某些http请求中,从内存中返回数据而不是让它到达服务器.我知道我可以编写http拦截器,但我不确定如何从请求中实际返回响应? myModule.factory('myHttpInterceptor',function ($q) { return { // optional method 'request': function (config) { //
我希望,在某些http请求中,从内存中返回数据而不是让它到达服务器.我知道我可以编写http拦截器,但我不确定如何从请求中实际返回响应?
myModule.factory('myHttpInterceptor',function ($q) { return { // optional method 'request': function (config) { // return my data here [200],and stop the call from going through return config; } }; }); 解决方法
这是一个只使用拦截器的解决方案.我仍然认为评论中的érics解决方案更优雅,但现在你有不同的选择要考虑.
app.factory('myHttpInterceptor',function ($q,myCache) { return { request: function (config) { var cached = myCache.getCachedData(config.params); if(cached){ return $q.reject({cachedData: cached,config: config }); } return config; },response: function(response){ // myCache.saveData(response.data); },responseError: function(rejection) { if(rejection.cachedData){ return $q.resolve(rejection.cachedData); } return $q.reject(rejection); } }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读