我怎么知道 $http 响应是否来自缓存 - Angular

How can I know if the $http response is brought from cache - Angular

如果响应来自缓存,$http是否有任何指示?
例如,假设我打了这两个电话:

$http.get({url, cache: true).then(function(response, ..., moreData) { alert(moreData.fromCache) }) //alerts false 

$http.get({url, cache: true).then(function(response, ..., moreData) { alert(moreData.fromCache) }) //alerts true

如您所见,第一个调用实际上是在执行一个 ajax 调用,因此它不是来自缓存,第二个调用从缓存中获取数据,因此它警报为 true

我不确定是否公开了信息 - 文档提到即使资源被缓存,请求(使用缓存)仍然是异步的,所以它看起来像任何其他请求。我唯一能想到的就是滚动你自己的缓存并使用它来知道何时发生了成功的查找。来自文档:

You can change the default cache to a new object (built with $cacheFactory) by updating the $http.defaults.cache property. All requests who set their cache property to true will now use this cache object.

您可以通过 Chrome 开发人员工具查看“网络”选项卡来查看调用是否已缓存。它会告诉你它是否被缓存或是否被调用。

很容易确定某些内容是否与请求和响应处理程序一起缓存,但需要注意。此 ONLY 处理第一个请求完成 BEFORE 第二个请求完成的情况。如果您在第一个返回之前进行 2 requests,angular 缓存将像魅力一样处理并且只进行 1 次服务调用,两者都将显示为未缓存,这在技术上是正确的,因为它们是都在等待第一个请求被缓存,但可能不是你想要的。

$httpProvider.interceptors.push(function() {
    return {
        'request': function requestInterceptor(config) {
            if (config.cache) {
                //Determine if a custom cache object is being used
                var cache = angular.isObject(config.cache) ? config.cache : $http.defaults.cache;
                config.wasCached = cache.get(config.url) ? true : false;
            }

            return config;
        },

        'response': function(response) {
            if (response && response.config && response.config.wasCached) {
                console.log('Was Cached!')
            } 
            return response;
        }
    };
});