gpt4 book ai didi

angular-cli - Angular5 PWA 不刷新(Service Workers)

转载 作者:行者123 更新时间:2023-12-03 07:45:17 26 4
gpt4 key购买 nike

我正在使用 angular5 开发一个应用程序,通过 ng-cli 使用服务工作人员,但我意识到在第一次加载应用程序 shell 后,它不会刷新。使用 ng build 构建应用程序后,如何将新文件版本推送到我的应用程序?我可以直接手动重写 sw.js,但由于它是通过 cli 生成的,我不喜欢影响任何我不知道其用途的东西。

我一整天都在寻找这个答案,但由于 Service Worker 对于 1.6 版本的 ng-cli 来说是新的,所以我还没有找到任何答案。

我什至在 ng-cli 1.6 之前找到了一个与 Angular 4 类似的线程和一个非官方的 Service Worker 实现,但我不信任这种方法,因为它不是官方的,所以我想知道你们是否可以帮助我找到一种方法来控制它安装 shell 和查找新版本的方式。

谢谢

最佳答案

这对我有用。这有助于浏览器检测到应用程序有新版本。

App.component.ts:

    import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

constructor(public updates:SwUpdate) {
updates.available.subscribe(event => {
console.log('current version is', event.current);
console.log('available version is', event.available);
});
updates.activated.subscribe(event => {
console.log('old version was', event.previous);
console.log('new version is', event.current);
});

updates.available.subscribe(event => {
updates.activateUpdate().then(() => this.updateApp());
});
}

updateApp(){
document.location.reload();
console.log("The app is updating right now");

}
}

还有

ngsw.json:

{
"index": "/index.html",
"assetGroups": [
{
"name": "Your app",
"installMode": "prefetch",
"updateMode": "lazy",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "prefetch",
"updateMode": "lazy",
"resources": {
"files": [
"/assets/**"
],
"urls":[
"https://urlsyouwanttocachefrom.com/**",
]
}
}
]
}

这样,每次更新应用程序时,浏览器都会自动重新加载。

关于angular-cli - Angular5 PWA 不刷新(Service Workers),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com