📅  最后修改于: 2022-03-11 14:48:30.428000             🧑  作者: Mango
// You will probably need to tell the service worker to check the server for updates, I usually use a service for this:
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());
}
// In your app-component.ts:
constructor(private sw: UpdateService) {
// check the service worker for updates
this.sw.checkForUpdates();
}
// For whatever reason, Angular sometimes does not register the service worker properly. So you can modify `main.ts` :
// Replace:
// platformBrowserDynamic().bootstrapModule(AppModule);
// With:
platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('ngsw-worker.js');
}
}).catch(err => console.log(err));