node.js - Angular PWA - 在没有可用连接时路由到自定义离线页面
问题描述
在 Angular PWA 中,如果没有可用的互联网连接,我想将用户重定向到自定义离线页面 (offline.html)。
使用该ng-sw.config.json
文件,我设置了要缓存的资产和 API 以及使用哪种策略(性能/新鲜度),即使在离线时我也可以为应用程序提供服务而没有任何问题。现在我想展示一个自定义的离线页面,但在教程和指南中,我看不到使用 Angular 及其 service-worker 模块实现此目的的方法。
我想知道是否可能的解决方案是创建一个检查连接性(在线/离线)的服务,如果离线,它会重定向到 offline.html 页面。服务和 html 页面将使用“预取”策略进行缓存,以确保它们在安装服务工作者后立即可用。
否则,我将创建一个基础服务工作者,它会导入默认的 Angular 服务工作者,并在 fetch 调用失败时添加逻辑以重定向到离线页面。
还有其他可能吗?
解决方案
首先,您需要创建一个离线 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);
}
});
})
);
});
}
因此,当用户处于离线模式并且用户尝试导航到另一条路线时,他们将看到离线页面
推荐阅读
- raku - 在 Perl 6 中打印对象
- jekyll - 在 Jekyll 中哪里可以找到默认布局
- angular - Angular Elements 脚本导入与元素参考位置
- solr - 如何使用 SolrJ API 创建一个不洗牌 createNodeSet 主机的 Solr 集合?
- elixir - 批量处理事件 Elixir Flow
- aws-kms - 为什么 AWS/KMS 将 ListAliases 限制为当前账户?
- javascript - 无法将 d3 向量附加到传单地图
- c++ - C++中带有向量的双向链表构造函数
- c++ - 将 usart 接收到的 uint8_t* 数据与常量字符串进行比较
- javascript - 如何使用 React 渲染用户之前的会话?