Angular PWA-当没有可用连接时路由到自定义脱机页面 [英] Angular PWA - Route to custom offline page when no connection available

查看:58
本文介绍了Angular PWA-当没有可用连接时路由到自定义脱机页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有可用的Internet连接,我想在Angular PWA中将用户重定向到自定义的脱机页面(offline.html).

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.

使用ng-sw.config.json文件,我设置了要缓存的资产和API以及要使用的策略(性能/新鲜度),即使脱机时也可以毫无问题地为应用程序提供服务. 现在,我想显示一个自定义的脱机页面,但是在教程和指南中,我看不到使用Angular及其service-worker模块实现此目的的方法.

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.

我想知道一种可行的解决方案是否是创建一种检查连接性(联机/脱机)的服务,如果该服务处于脱机状态,则将其重定向到offline.html页面.服务和html页面将使用预取"策略进行缓存,以确保在安装服务工作程序后立即可用.

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.

否则,我将创建一个基础服务工作程序,该工作程序将导入默认的Angular服务工作程序,并添加逻辑,以便在提取调用失败时重定向到脱机页面.

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.

还有其他可能性吗?

推荐答案

首先,您需要创建一个脱机html页面并将其存储在资产文件夹中.

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

然后将该脱机页面添加到您的ng-sw.config中

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

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

接下来在您的app.component.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

这篇关于Angular PWA-当没有可用连接时路由到自定义脱机页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆