Angular Service Workers
Service workers enable Progressive Web App (PWA) features, such as offline support, push notifications, and background data synchronization. This guide covers the basics of setting up and using Angular service workers.
Setting Up Angular Service Workers
First, add the Angular PWA package to your project:
ng add @angular/pwa --project my-app
This command configures your Angular app with the necessary files and settings to use service workers.
Configuring Service Workers
Angular service worker configuration is managed in the ngsw-config.json
file. Here's an example configuration:
// ngsw-config.json
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.png"
]
}
}
]
}
Building the Project
Build your project to include the service worker:
ng build --prod
This command generates the necessary files in the dist
folder, including the service worker file.
Registering the Service Worker
Register the service worker in your Angular app:
// src/main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
// Register the service worker
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('/ngsw-worker.js');
}
Using Service Worker Features
Angular service workers provide various features, such as caching strategies, push notifications, and background synchronization:
Caching Strategies
Define caching strategies in the ngsw-config.json
file:
// ngsw-config.json
{
...
"dataGroups": [
{
"name": "api-freshness",
"urls": [
"/api/**"
],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "1d"
}
}
]
}
Push Notifications
Implement push notifications using the Angular service worker:
// app.component.ts
import { SwPush } from '@angular/service-worker';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
readonly VAPID_PUBLIC_KEY = 'YOUR_PUBLIC_VAPID_KEY';
constructor(private swPush: SwPush) {
this.subscribeToNotifications();
}
subscribeToNotifications() {
this.swPush.requestSubscription({
serverPublicKey: this.VAPID_PUBLIC_KEY
})
.then(subscription => {
console.log('Notification subscription: ', subscription);
// Send subscription to the server
})
.catch(err => console.error('Could not subscribe to notifications', err));
}
}
Background Synchronization
Use background synchronization to handle background data synchronization:
// service-worker.js
self.addEventListener('sync', event => {
if (event.tag === 'sync-data') {
event.waitUntil(syncData());
}
});
async function syncData() {
// Perform background data synchronization
}
Key Points
- Add the Angular PWA package to your project to enable service workers.
- Configure the service worker in the
ngsw-config.json
file. - Build your project with the
--prod
flag to include the service worker. - Register the service worker in your Angular app.
- Use Angular service worker features such as caching strategies, push notifications, and background synchronization.
Conclusion
Angular service workers enable powerful Progressive Web App features that enhance the user experience by providing offline support, push notifications, and background data synchronization. By setting up and configuring Angular service workers, you can create robust and responsive Angular applications. Happy coding!