Angular.io interceptors vs service workers
Asked Answered
U

2

7

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?

Uribe answered 4/1, 2018 at 17:28 Comment(0)
E
12

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.

Edrick answered 5/1, 2018 at 16:25 Comment(0)
B
0

Angular service worker introduction Link

Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as fetch; it also includes resources referenced in HTML and even the initial request to index.html. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.

Unlike the other scripts that make up an application, such as the Angular application bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can completely satisfy the loading of the application, without the need for the network.

Bionomics answered 17/7, 2022 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.