【问题标题】:In Angular 9, how to only use cache for an http get request if navigator is not online在 Angular 9 中,如果导航器不在线,如何仅将缓存用于 http get 请求
【发布时间】:2020-10-14 04:22:46
【问题描述】:

我有一个 Angular 9 应用程序,它使 http.get 调用 API。我已经实现了 angular-pwa 以允许离线功能。

我很难弄清楚当浏览器在线时,我不想将缓存的响应用于 2 个给定的请求。

我尝试设置我的 ngsw-config.json

...

"dataGroups": [
        {
            "name": "api-performance",
            "urls": [
                "**/assets/**",
                "**/api/**",
                "**/materialicons/**"
            ],
            "cacheConfig": {
                "strategy": "performance",
                "maxAge": "12h",
                "maxSize": 200,
                "timeout": "50s"
            }
        },
        {
            "name": "api-freshness",
            "urls": ["**/api/always-get-fresh**", "**/api/always-get-fresh2**"],
            "cacheConfig": {
                "strategy": "freshness",
                "maxAge": "12h",
                "maxSize": 200,
                "timeout": "50s"
            }
        }
    ]

.... 对我想要新鲜的 2 个特定 http 使用新鲜度策略,我指定其余的为性能。

我也尝试在导航器重新上线时删除缓存

在 app.component.ts 中

addEventListener('online', (e) => {
            caches.keys().then((cacheNames) => {
                return Promise.all(
                    cacheNames
                        .filter((cacheName) => {
                          return true;
                        })
                        .map((cacheName) => {
                            if (cacheName.search('api-freshness') !== -1) {
                                return caches.delete(cacheName);
                            }
                            return false;
                        })
                );
            });


        });

到目前为止,两次尝试都没有成功。

【问题讨论】:

    标签: angular


    【解决方案1】:

    原来问题出在数据组的顺序上。

    我把性能放在新鲜度之后,除非离线,否则 2 个 http 获取总是调用服务器。

    删除缓存部分没用,我删除了它。

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2017-10-09
      • 1970-01-01
      • 2019-11-08
      相关资源
      最近更新 更多