Overriding Angular's Service Worker to handle POST requests
The problem here is not about angular's service workers, it is a common problem which actually service workers can't solve.
The PWA structure let the browsers to cache the app itself (.css .html .js files, images and so son). All these are static data which are retrieved with GET
HTTP requests.
Now, when we use the PWA structure to cache some data we GET
from a rest API, we are doing something a bit tricky... it works, ok.
The problems with calls which modify data in offline mode are more... think to concurrency between changes performed by different users. More simply, think to the following calls sequence
GET /data/42 // to retrieve an objectPOST /data/42 // to update the objectGET /data/42 // to retrieve the same object
when online we expect that the first and the third calls (actually the same call) have two distinct response. How could a service worker replicate this scenario when in off line mode? It should at least know the logic of the called API, but even if we teach the logic to our service worker, how could it predict errors which could be raised during the second and the third calls?
The proper way to handle data in a PWA which plans to work with data in off line mode as well, is to implement a client side data layer (using localStorage
or IndexedDB
) which, when offline, remembers the changes attempts and try to sync them when back to on line mode.