Angular PWA - Route to custom offline page when no

2020-04-21 02:18发布

问题:

In an Angular PWA I would like to redirect the user to a custom offline page (offline.html) if there is no internet connection available.

Using the ng-sw.config.json file I setup the assets and APIs to be cached and which strategy to use (performance/freshness) and I could serve the application even when offline without any problems. Now I would like to show a custom offline page, but among tutorials and guides I could not see a way to achieve this with Angular and its service-worker module.

I am wondering whether a possible solution would be to create a service that checks the connectivity (online/offline) and, if offline, it redirects to offline.html page. Service and html page would be cached with a 'prefetch' strategy to ensure they are available as soon as the service worker is installed.

Otherwise I would create a base service worker that imports the default Angular service worker and adds logic to redirect to the offline page if the fetch call fails.

Are there any other possibilities?

回答1:

First you need to create a offline html page and store in assets folder.

Then add that offline page into your ng-sw.config like this

  "resources": {
    "files": [
      "/assets/favicon.ico",
      "/*.css",
      "/*.js",
      "/assets/offline-page.html"  
    ],

Next in your app.component.html add logic like this

ngOnInit() {
  self.addEventListener('fetch', function(event) {
    return event.respondWith(
      caches.match(event.request)
      .then(function(response) {
        let requestToCache = event.request.clone();

        return fetch(requestToCache).then().catch(error => {
          // Check if the user is offline first and is trying to navigate to a web page
          if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
            // Return the offline page
            return caches.match(offlineUrl);
          }
        });
      })
    );
  });
}

So when user are in offline mode and user try to navigate to another route they will see offline page