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": ["/**"],
"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:
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./**"],
"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:
4 Answers
Reset to default 6Try this:
- Go to your application tab -> Clear Storage -> Clear Site Data.
Change your DataGroups array from this:
{ "name": "api", "urls": ["https://x./**"], "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
if you are using "strategy": "performance" remove timeout property
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./Alorel/ngforage#types-and-polyfills
https://developers.google./web/fundamentals/instant-and-offline/web-storage/offline-for-pwa
"dataGroups": [
{
"name": "TestApi",
"urls": [
"https://api.chucknorris.io/jokes/random",
"https://localhost:4377/api/home/getNames/"
],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 20,
"maxAge": "1h",
"timeout": "5s"
}
},
{
"name": "TestAPI",
"urls": [
"https://localhost:4377/api/test/getList",
"https://localhost:4377/api/template/start/"
],
"cacheConfig": {
"strategy": "performance",
"maxSize": 20,
"maxAge": "2h",
"timeout": "5s"
}
}
]