Blog>
Snippets

Dynamic Content Caching Strategies

Demonstrate how to cache dynamic content by implementing appropriate caching strategies in Angular with the help of service workers.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CacheService {
  private cache = new Map();

  constructor(private http: HttpClient) {}

  // Retrieves data from cache or fetches it from the network
  getData(url: string) {
    const cachedResponse = this.cache.get(url);
    if (cachedResponse) {
      return of(cachedResponse); // Return cached data as an observable
    }

    return this.http.get(url).pipe(
      tap(response => {
        this.cache.set(url, response); // Cache the response
      })
    );
  }
}
CacheService definition that provides a method to fetch data with a simple caching mechanism using a Map. If data is cached, it returns the cached value, otherwise it fetches from the network and caches the response.
import { SwUpdate, SwPush } from '@angular/service-worker';

@Component({...})
export class AppComponent {
  constructor(updates: SwUpdate, push: SwPush) {
    updates.available.subscribe(event => {
      updates.activateUpdate().then(() => document.location.reload());
    });
  }

  // other component logic
}
AppComponent that subscribes to updates from the Angular Service Worker. When an update is available, it activates the update and reloads the page to ensure the client is using the latest version of the app.
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    HttpClientModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
      // Register the Angular Service Worker
      registrationStrategy: 'registerWhenStable:30000'
      // Register after the app is stable for 30 seconds
    })
  ]
  // ... other module definitions
})
export class AppModule { }
AppModule class where the ServiceWorkerModule is imported and registered with a strategy that waits for the application to be stable for 30 seconds before registering the service worker. This is done in production mode only.