可以使用 ServiceWorkerModule
模块提供的 SwUpdate
服务来更新和控制 Service Worker。在运行时,我们可以调用 SwUpdate
服务的 activateUpdate()
方法来清除 Service Worker 的缓存。
代码示例:
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(private swUpdate: SwUpdate) { if (swUpdate.isEnabled) { swUpdate.available.subscribe(() => { if(confirm("New version available. Load New Version?")) { window.location.reload(); } }); } }
clearCache() { if (this.swUpdate.isEnabled) { this.swUpdate.activateUpdate().then(() => { console.log('Clearing cache!'); window.location.reload(); }); } } }
在 AppComponent
中,我们注入了 SwUpdate
服务,并检查是否可用。我们可以使用 swUpdate.available
订阅器来监听新版本是否可用,并在用户确认后刷新页面以加载新版本。
另外,我们还添加了 clearCache()
方法,该方法调用 SwUpdate
服务的 activateUpdate()
方法来清除 Service Worker 的缓存。调用成功后,我们使用 window.location.reload()
方法刷新页面以加载最新版本。