我正在开发一个角度为4的渐进式网络应用程序,它似乎在在线模式下正常工作。它也适用于离线模式,除非我涉及动态缓存。
所以我在ngsw-manifest.json
进行了一些配置:
{
"routing": {
"index": "/index.html",
"routes": {
"/": {
"match": "exact"
},
"/coffee": {
"match": "prefix"
}
}
},
"static.ignore": [
"^\/icons\/.*$"
],
"external": {
"urls": [
{
"url": "https://fonts.googleapis.com/icon?family=Material+Icons"
},
{
"url": "https://fonts.gstatic.com/s/materialicons/v29/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2"
}
]
},
"dynamic": {
"group": [
{
"name": "api",
"urls": {
"http://localhost:3000/coffees": {
"match": "prefix"
}
},
"cache": {
"optimizeFor": "freshness",
"networkTimeoutMs": 1000,
"maxEntries": 30,
"strategy": "lru",
"maxAgeMs": 360000000
}
}
]
}
}
因此上面json中的dynamic
密钥缓存页面上的内容以供离线使用。
以下是缓存内容的图像:
但是,当我尝试在缓存后以脱机模式重新加载页面时,内容未显示。我错过了一些配置吗?
答案 0 :(得分:0)
在等待ngsw
准备就绪时,您可以在Angular项目中使用workbox-build
npm包。
预先缓存资产:
const workbox: WorkboxBuild = require('workbox-build');
workbox.injectManifest({
globDirectory: './dist/',
globPatterns: ['**\/*.{html,js,css,png,jpg,json}'],
globIgnores: ['build/*', 'sw-default.js', 'workbox-sw.js','assets/icons/**/*'],
swSrc: './src/sw-template.js',
swDest: './dist/sw-default.js',
});
对于动态缓存:
const workboxSW = new self.WorkboxSW();
// work-images-cache
workboxSW.router.registerRoute('https://storage.googleapis.com/xxx.appspot.com/(.*)',
workboxSW.strategies.cacheFirst({
cacheName: 'work-images-cache',
cacheExpiration: {
maxEntries: 60
},
cacheableResponse: { statuses: [0, 200] }
})
);
您可以通过调用另一个registerRoute
来缓存网络字体等。现实用法示例here。
答案 1 :(得分:0)
当我使用相同的配置时,即使我遇到同样的问题。 下面为我解决了,我能够在离线模式下从缓存中检索咖啡列表 在ngsw-config.json中使用“dataGroups”进行动态缓存,如下所示
"dataGroups":[
{
"name":"api",
"urls":[
"/coffees"
],
"cacheConfig": {
"strategy": "performance",
"timeout": "10s",
"maxSize": 30,
"maxAge": "1d"
}
}
]
以下文章可能会有所帮助