Search code examples
angularprogressive-web-appsngrx

Angular PWA and NGRX.. fetch data if offline


I would like to ask if there is a way where i could still retrieve data using ngrx even if the angular app is down due to network or no internet. the idea is like.. if no internet then pull default data that have been saved in the store so far.


Solution

  • For a minimalistic PWA, you need to do following:

    First you register the service worker with:

    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/serviceworker.js').then(function(registration) {
            // Registration was successful
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
          }, function(err) {
            // registration failed :(
            console.log('ServiceWorker registration failed: ', err);
          });
        });
      }
    

    First you check if its even available in your browser. If it is, then you need to pass the path to your service worker. In this example its /serviceworker.js.

    Remember: Registration wont work if you are using HTTP or the file system C:// you need to use either HTTPS or with localhost it should work too.

    Now the service worker part. With this exmaple you will cache every page you visit, and if you turn off your network it should still work.

    //serviceworker.js
    
    var CACHE_NAME = "my_cache_v1";
    
    self.addEventListener('fetch', function(event) {
        event.respondWith(
          caches.match(event.request)
            .then(function(response) {
              // Cache hit - return response
              if (response) {
                return response;
              }
      
              return fetch(event.request).then(
                function(response) {
                  // Check if we received a valid response
                  if(!response || response.status !== 200 || response.type !== 'basic') {
                    return response;
                  }
      
                  // IMPORTANT: Clone the response. A response is a stream
                  // and because we want the browser to consume the response
                  // as well as the cache consuming the response, we need
                  // to clone it so we have two streams.
                  var responseToCache = response.clone();
      
                  caches.open(CACHE_NAME)
                    .then(function(cache) {
                      cache.put(event.request, responseToCache);
                    });
      
                  return response;
                }
              );
            })
          );
      });
    

    You can do more with PWA. You can ask the user to install your app, or you can subscribe user to Push notifications. Actually i work on a small library that should simplify that for you you can check it out here: (still under development)

    https://github.com/ilijanovic/serviceHelper

    https://www.npmjs.com/package/servicehelper

    To make it installable you would need to include a manifest to your site with the essential properties.