Angular Service Worker, caching api calls for offline app

白昼怎懂夜的黑 提交于 2019-12-10 17:11:34

问题


I'm trying to make the service worker in angular work with API requests. I'd like the app to work offline and I've the below config:

    {
        "name": "api",
        "urls": ["https://x.com/**"],
        "cacheConfig": {
            "strategy": "performance",
            "maxSize": 20,
            "maxAge": "365d",
            "timeout": "5s"
        }
    }

Here is what the xhr tab looks like when I'm offline:

and this is the content of the user request:

As you can see the API calls for user don't resolve.

This is what the response of user looks like when online:


回答1:


Try this:

  • Go to your application tab -> Clear Storage -> Clear Site Data.
  • Change your DataGroups array from this:

    {
        "name": "api",
        "urls": ["https://x.com/**"],
        "cacheConfig": {
            "strategy": "performance",
            "maxSize": 20,
            "maxAge": "365d",
            "timeout": "5s"
        }
    }
    

To this:

"dataGroups": [
    {
      "name": "api-performance",
      "urls": [
        "/user" //<=========== I know you want all API calls to be cached, but try this first and see
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ]
  • save and build your app in PROD,
  • visit the page the first time.
  • disable network
  • refresh your page



回答2:


if you are using "strategy": "performance" remove timeout property




回答3:


To handle API data offline you have to use Offline Storage (that is store data in web browser after initial API call), recently I have used Local Forage in my application. Find the linkS below:

https://github.com/Alorel/ngforage#types-and-polyfills

https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/offline-for-pwa



来源:https://stackoverflow.com/questions/48419769/angular-service-worker-caching-api-calls-for-offline-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!