简体   繁体   English

使用 Angular Service Worker 预取 API 数据(dataGroups)

[英]Prefetch API data (dataGroups) using Angular Service Worker

I have an Angular website that needs to work offline.我有一个需要离线工作的 Angular 网站。 Part of what it needs is some data from the API.它需要的部分数据来自 API。 This can be stale data, so my strategy is to try the API, if that fails, then get it from the cache.这可能是陈旧的数据,所以我的策略是尝试 API,如果失败,则从缓存中获取。

I set this up using the dataGroups :我使用dataGroups进行了设置:

"dataGroups": [
    {
        "name": "offlineData",
        "urls": [ "/api/offline" ],
        "cacheConfig": {
            "maxSize": 1000,
            "maxAge": "100d",
            "timeout": "500u",
            "strategy": "freshness"
        }
    }
]

However, if a user installs the app (using the manifest), and immediately go offline, the API data doesn't exist in the cache as dataGroups doesn't prefetch.但是,如果用户安装应用程序(使用清单),并立即离线 go,则缓存中不存在 API 数据,因为 dataGroups 不预取。

So where is the correct place that I should hook into and fetch the data?那么我应该挂钩并获取数据的正确位置在哪里? I've tried in the app.component , and in the ServiceWorker Update Service (which is really the same as the app.component as it gets called from there).我已经在app.component和 ServiceWorker 更新服务中尝试过(它与app.component从那里被调用时完全相同)。

Either way, this seems to call the API before the service worker configuration has been processed, so it doesn't get added to the cache.无论哪种方式,这似乎在处理服务工作者配置之前调用 API,因此它不会被添加到缓存中。

What is the appropriate lifecycle hook to add this to, so that it performans a prefetch which the ngsw config will then be aware of?将其添加到哪个合适的生命周期钩子,以便它执行 ngsw 配置将知道的prefetch

on the initialization of the app, you can add your data to the localstorage .在应用程序初始化时,您可以将数据添加到localstorage localstorage stores the data tab wise. localstorage 以选项卡方式存储数据。 That means each tab would have their specific data in the localstorage.这意味着每个选项卡都将在本地存储中具有其特定数据。

So when the api fails due to network connection.所以当api由于网络连接失败时。 You can use the data stored in the localstorage .您可以使用存储在localstorage中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM