I want to better understand options to implement offline-friendly webapps and I read this article here: https://angular.io/guide/http which also talks about angular's interceptors.
Now I am a bit puzzled:
On one hand we have service workers (that are not yet fully supported by browsers) which would help implement offline first/friendly apps, on the other we have this powerful tool - interceptors - which can do a lot of things to help apps better handle poor or no connection environments.
So is there a clear understanding of difference between these 2? when to use one and when to use another?
Adding a service worker to an Angular application is one of the steps for turning an application into a Progressive Web App (also known as a PWA). At its simplest, a service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy.
The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators. The interceptors do not initiate the handle method and handle the requests at their level.
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response.
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
HttpClient
interceptors and service workers are different layers.
HttpClient
interceptors handle only requests that are performed with HttpClient
provider within particular Angular application.
Service workers handle all requests that are performed in browser window, including the page itself, assets and AJAX (XHR
and Fetch
) requests.
The only common use they have is HttpClient
request to remote API.
Since API requests can be handled at different places in Angular application, it's up to developer which one is appropriate. A fallback due to failed request may occur in service worker, HttpClient
interceptor or a service that uses HttpClient
.
Considering that a problem can be solved in multiple ways, and browser support matters, service workers won't be the first choice. If a problem cannot be solved with HttpClient
alone or the solution is impractical, this is a job for service workers. For instance, the use of AJAX to transfer base64 images when binary files would be more appropriate.
The fact that service workers don't block main thread can also be a major concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With