Angular Service Worker SwUpdate.available not triggered
I found the following info in the angular docs: https://angular.io/guide/service-worker-devops#debugging-the-angular-service-worker
Summary: There's a useful endpoint on angular sites that shows the service worker state:
http://site-url/ngsw/state
Append /ngsw/state
to your sites address. If there is something wrong with the service it should show there.
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));
After every other solution on the stack didn't work, I've started debugging angular's ngsw-worker.js script. I've traced the updating logic and ended up in the "PrefetchAssetGroup" method. I've inserted logging every time method got called and then I realized that it is constantly trying to cache my favicon.ico. I've checked the location of the favicon.ico in my ngsw.json and realized that favicon is not located there. Once I've placed the icon on that location everything started working fine.