I have made a PWA using Angular. The PWA works fine, caching works. When going offline all the needed API calls are saved into the cache and accessed by the service worker.
My question is simple, how can I access this data on command.
It's great that the service-worker does this for me when the PWA goes offline however, this data that is in cache is data that I want other components to use. Considering that it is allready in cache I don't want to have to make the API call again.
I was researching the different options and I couldn't really find anything conclussive. The caching API seemed interesting but I have no clue if that is how an Angular PWA saves its data.
So, Anyone know how to access the cached data that a service-worker uses?
Inside my ngsw-config.json file, where I delcared my datagroups. I gave the group a name, in this case 'mission-api'.
"dataGroups": [
{
"name": "mission-api",
"urls": ["https://12goappapi.azurewebsites.net/api"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 20,
"maxAge": "1h",
"timeout": "5s"
}
}
]
Using the cashing API, you are able to read the cached data. The service worker actually uses those same calls. To access the data that you save, all you need is the caching name.
Now this is were I was struggling, the name is not just the name you specify. The ngsw-worker.js adds a bunch of pre-fix before the name in order to be sure that the name is unique.
For me personally I had to open a browser and check to see what the name was.
When you find the corresponding name you can use the cache API to retrieve your data. I feel like their should be a better way to find/determine this name. If somebody finds it feel free to update my answer or provide one of your own!
for instance:
if ('caches' in window) {
console.log('CACH API ENABLED IN BROWSER');
caches.open('ngsw:/:1:data:dynamic:mission-api:cache').then(cache => {
cache.match('https://12goappapi.azurewebsites.net/api/missions').then(res => {
res.json().then(result => {
console.log(result);
this.missions = result;
});
})
});
}