Angular PWA - Route to custom offline page when no connection available

巧了我就是萌 提交于 2019-12-13 03:44:49

问题


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



来源:https://stackoverflow.com/questions/56735905/angular-pwa-route-to-custom-offline-page-when-no-connection-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!