Blog>
Snippets

Using Angular Service Workers for Offline Capabilities

Provide an example of configuring a service worker in Angular to cache assets for offline access, improving mobile experience in poor network conditions.
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    // Other module imports
    // ...
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
      // Register the ServiceWorker as soon as the app is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000'
    }),
  ],
  //...
})
export class AppModule { }
This code snippet is part of the Angular module configuration, where the ServiceWorkerModule is imported from '@angular/service-worker' and registered in the imports array. It uses 'ngsw-worker.js', which is the default file name for the Angular service worker. The 'enabled' property turns on service workers only in production mode, as indicated by 'environment.production'. The 'registrationStrategy' option ensures that the service worker is registered once the app is stable or after 30 seconds.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Injectable({
  providedIn: 'root',
})
export class CheckForUpdateService {
  constructor(updates: SwUpdate) {
    updates.available.subscribe(event => {
      if (confirm('New version available. Load New Version?')) {
        updates.activateUpdate().then(() => document.location.reload());
      }
    });
  }
}
In this code snippet, a service called CheckForUpdateService is created. This service uses the SwUpdate service from Angular's service-worker module to subscribe to update events. When a new update is available, it prompts the user for confirmation. If the user confirms, the service worker activates the update and reloads the page to display the updated content.
import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Component({
  // component's metadata
})
export class AppComponent {
  constructor(private swUpdate: SwUpdate) {
    if (this.swUpdate.isEnabled) {
      this.swUpdate.available.subscribe(() => {
        if (confirm('A new version of the app is available. Load it?')) {
          window.location.reload();
        }
      });
    }
  }
}
This code snippet is part of an Angular component that checks for updates using the service worker. The constructor injects the SwUpdate service, and if service workers are enabled, it subscribes to the 'available' updates. When an update is detected, it prompts the user to reload the app to apply the latest updates.