I am using Angular5
and angular service worker
.
I cached
some data and some assets and everything is working fine as expected and even deployed the code.
Now, if I update some code and deploy again, the service worker
doesnot get updated.
So, I had gone through Angular service worker link and I Implemened SwUpdate service
.
Here is my code:
I created a service and called it in App Component
import { Injectable, NgZone } from '@angular/core';
import { interval } from 'rxjs/observable/interval';
import { SwUpdate } from '@angular/service-worker';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class ServiceWorkerService {
constructor(updates: SwUpdate, ngZone: NgZone) {
console.log('Servicee worker update called');
updates.available.subscribe(event => {
console.log('current version is', event.current);
console.log('available version is', event.available);
updates.activateUpdate().then(() => document.location.reload());
});
updates.activated.subscribe(event => {
console.log('old version was', event.previous);
console.log('new version is', event.current);
});
ngZone.runOutsideAngular(() => {
interval(6000).subscribe(() => {
console.log('Inside Interval')
ngZone.run(() => updates.checkForUpdate());
});
});
}
}
What the above code does:
subscribes
to updates.available
event.Issue:
Now, the issue is, it is working perfectly on chrome. But not in firefox. In firefox, the code is not comming inside
updates.available.subscribe
I had this same issue and was able to fix it by registering the service worker in main.ts
:
platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('/ngsw-worker.js');
}
}).catch(err => console.log(err));
I also created a Service worker service to notify the user when there is a new update available:
If you are interested in how my service worker service looks, you can see the code here.
You can also check if any errors have been logged by visiting yourdomain.com/ngsw/state
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With