I'm trying to use service-worker with my Angular Application. It is build using webpack.
I use workbox-webpack-plugin. I want to serve my GET API calls form cache and in the background update the data.
FOr this, I use the option runtimeCaching
with the handler staleWhileRevalidate
(more details on GenerateSW plugin here)
This is the config I have in webpack.config.js:
new GenerateSW({
// importWorkboxFrom: 'local',
clientsClaim: true,
skipWaiting: true,
navigateFallback: '/index.html',
runtimeCaching: [
{
// Match any same-origin request that contains 'api'.
urlPattern: /https:\/\/api.*/,
handler: 'staleWhileRevalidate',
options: {
cacheName: 'api',
broadcastUpdate: {
channelName: 'api-updates',
},
// Add in any additional plugin logic you need.
plugins: [],
},
}
]
}),
According to this documentation, I should be able to receive an event when the cache is updated (I want to display something to the user so he can refresh the data).
The code to receive the data look like this:
export class AppComponent implements OnInit {
public ngOnInit() {
console.log( 'AppComponent - ngOnInit' );
const updatesChannel = new BroadcastChannel('api-updates');
updatesChannel.addEventListener('message', async (event) => {
console.log('Event received');
});
}
}
I put this code inside one of my Angular component, it never got called even if I'm sure that the cache was updated.
I think it might have something to do with how change detection works in Angular (like described in this question) but I'm not sure how to fix it.
Did anyone manage to successfully listen to broadcast event from Angular component ?