我希望,在某些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;
}
};
});
Run Code Online (Sandbox Code Playgroud)
这是一个只使用拦截器的解决方案.我仍然认为评论中的É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);
}
};
});
Run Code Online (Sandbox Code Playgroud)