angular - Angular Service Worker SwUpdate.available 未触发
问题描述
我很难将 angulars service worker 集成到我的应用程序中。我按照指南进行了操作,到目前为止它仍然有效。我可以在我的主屏幕上创建一个快捷方式并启动我的应用程序。问题是我的应用程序不知何故没有更新。如果我更改按钮的名称,构建应用程序并将其放到我的服务器上,该应用程序仍会显示旧版本,直到我按下 F5(重新启动应用程序也无济于事)。
我试图将以下代码放入我的应用程序的 ngOnInot 中,但它没有帮助
ngOnInit() {
if (this._SwUpdate.isEnabled) {
setInterval( () => {
this._SwUpdate.checkForUpdate().then(() => console.log('checking for updates'));
}, this.updateInterval);
this._SwUpdate.available.subscribe(() => {
console.log('update found');
this._SwUpdate.activateUpdate().then(() => {
console.log('updated');
window.location.reload();
});
});
}
}
该应用程序正在我的 apache2 linux 机器上运行。我的 apache 是否在缓存某些东西,或者为什么我的应用程序没有意识到有新版本?
在此先感谢您的帮助 :)
编辑:
我的 ngsw-config.json
{
"index": "/index.html",
"assetGroups": [{
"name": "roomPlan",
"installMode": "prefetch",
"resources": {
"files": [
"/index.html",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}]
}
编辑2:
如果我使用“http-server”在本地运行应用程序,它可以工作,但是当我将文件复制到我的 apache 时,它不会检测到更新。在网络选项卡中,我可以看到间隔有效,应用程序每 3 秒从服务器获取一个新的“ngsw.json”。如果我更新我的应用程序,我可以看到“ngsw.json”的响应中有新的哈希值。之后,浏览器从我的服务器加载新的“index.html”和“main.***.js”,但应用程序不应用新版本。根据我的代码,它应该说“找到更新”,但什么也没发生。
解决方案
您可能需要告诉服务人员检查服务器是否有更新,我通常为此使用服务:
export class UpdateService {
constructor(public updates: SwUpdate) {
if (updates.isEnabled) {
interval(6 * 60 * 60).subscribe(() => updates.checkForUpdate()
.then(() => console.log('checking for updates')));
}
}
public checkForUpdates(): void {
this.updates.available.subscribe(event => this.promptUser());
}
private promptUser(): void {
console.log('updating to new version');
this.updates.activateUpdate().then(() => document.location.reload());
}
在你的app-component.ts
:
constructor(private sw: UpdateService) {
// check the service worker for updates
this.sw.checkForUpdates();
}
无论出于何种原因,Angular 有时都没有正确注册 service worker。所以你可以修改 `main.ts` :
代替:
platformBrowserDynamic().bootstrapModule(AppModule);
和:
platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('ngsw-worker.js');
}
}).catch(err => console.log(err));
推荐阅读
- javascript - 我可以在每次函数运行 JavaScript 时声明一个新变量吗
- r - 如何减去两个时间变量之间的时间?
- utf-8 - 在 iTextPdf 中使用 UTF-8 字符串填充 AcroFields
- vue.js - 具有标准化数据的 Vuex getter 不是响应式的
- python - 在 numpy 中执行此操作的简单方法?
- c++ - c++ 是否在需要时将引用隐式转换为值?
- r - 主成分分析
- java - GUI 在 SwingWorker 线程中因长时间运行的任务而冻结
- python - 如果该值在可能的数字范围内,则为该值分配一个字母
- android - 存储库类中的协程范围