首页 > 解决方案 > Angular PWA - 在没有可用连接时路由到自定义离线页面

问题描述

在 Angular PWA 中,如果没有可用的互联网连接,我想将用户重定向到自定义离线页面 (offline.html)。

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

我想知道是否可能的解决方案是创建一个检查连接性(在线/离线)的服务,如果离线,它会重定向到 offline.html 页面。服务和 html 页面将使用“预取”策略进行缓存,以确保它们在安装服务工作者后立即可用。

否则,我将创建一个基础服务工作者,它会导入默认的 Angular 服务工作者,并在 fetch 调用失败时添加逻辑以重定向到离线页面。

还有其他可能吗?

标签: node.jsangulartypescriptsingle-page-applicationprogressive-web-apps

解决方案


首先,您需要创建一个离线 html 页面并存储在 assets 文件夹中。

然后像这样将该离线页面添加到您的 ng-sw.config 中

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

接下来在你的 app.component.html 添加这样的逻辑

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);
          }
        });
      })
    );
  });
}

因此,当用户处于离线模式并且用户尝试导航到另一条路线时,他们将看到离线页面


推荐阅读