I'm zeroing in on the core goal: building an Angular PWA with advanced caching. Currently, my focus is understanding the user's needs – they want service workers and sophisticated caching. This goes beyond the basics. I'm already exploring different caching strategies, considering the various options.
Analyzing the Architecture
My current mental map is focused on the architecture. I'm breaking down the key components: the Angular service worker, the ngsw-config.json file, and the core strategies. I'm identifying the building blocks of the tutorial, and I'm ensuring it's structured in a way that's easy to follow. I'm focusing on static and dynamic caching now, considering caching strategies.
Outlining the Structure
Now I'm creating a clear and logical structure for the guide, with setup, configuration, advanced strategies, update handling, and testing as key sections. I'm focusing on user-friendly explanations. I'm moving beyond the basics. My goal is to ensure readers can easily follow and implement the concepts.
Developing the Blueprint
My focus has shifted to detailed content. I'm now outlining sections on setup, configuration, advanced strategies (specifically static and dynamic caching), update handling, offline indicators, and testing. I'm moving beyond broad strokes and into providing code examples. I'm focusing on defining and structuring the key caching strategies, and how to best demonstrate them.
Developing the Code Examples
I'm now focused on the practical side, constructing the code snippets. The ngsw-config.json file needs careful attention, defining both static and dynamic caching. I'm building out the app.component.ts logic for handling updates and the user-facing offline indicators. I am moving towards the final touches.
This guide covers how to transform an Angular application into a robust Progressive Web App (PWA) using @angular/service-worker.
We will focus specifically on Advanced Caching Strategies for both static assets (images, fonts) and dynamic API data.
First, generate a new project (skip if you have one) and add the Angular PWA package. This setup automatically generates the manifest, icons, and the service worker configuration file.
bash
ng new advanced-pwa --routing --style=scss
cd advanced-pwa
# Adds @angular/service-worker, creates manifest.webmanifest, and ngsw-config.json
ng add @angular/pwa
Step 2: Understanding ngsw-config.json
The core of Angular specific caching lies in ngsw-config.json. It allows you to define two types of groups:
assetGroups: For static files (JS, CSS, Images).
dataGroups: For API calls (dynamic data).
Step 3: Advanced Caching Strategies
Open ngsw-config.json in your root directory. We will modify it to implement three distinct strategies.
Strategy A: The App Shell (Critical Static Assets)
We want the core app (HTML, main JS bundle, CSS) to be downloaded immediately (prefetch) so the app loads instantly offline.
Strategy B: Performance (Cache-First)
Best for data that doesn't change often (e.g., Product Catalogs, Blog Posts, Images). The app serves from the cache immediately for speed and updates the cache in the background.
Strategy C: Freshness (Network-First)
Best for user-specific or volatile data (e.g., User Settings, Stock Prices, Live Scores). The app tries to fetch from the network; if it fails (offline), it falls back to the cache.
strategy: 'performance': Cache-first. Shows data instantly. Use maxAge to determine when to consider the cache invalid.
strategy: 'freshness': Network-first. It waits for the network for 2s (timeout). If the network is too slow or offline, it serves the cached version.
maxSize: Important! Prevents the browser cache from bloating by rotating out old entries.
Step 4: Handling App Updates (UX)
Service Workers can be tricky. If you deploy a new version, users might still see the old one because it's served from the cache. You need to programmatically detect updates and prompt the user.
Open src/app/app.component.ts:
typescript
import { Component, OnInit } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private swUpdate: SwUpdate) {}
ngOnInit() {
// Check if Service Worker is enabled (it won't be in Dev mode)
if (this.swUpdate.isEnabled) {
// Subscribe to version updates
this.swUpdate.versionUpdates
.pipe(filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'))
.subscribe(evt => {
if (confirm('A new version of the app is available. Load it?')) {
// Reload the page to update to the latest version.
window.location.reload();
}
});
}
}
}
Step 5: Handling Online/Offline State
A PWA should visually verify to the user when they have lost connection.
In your app.component.ts (or a shared service):
typescript
import { Component } from '@angular/core';
import { fromEvent, merge, Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({ ... })
export class AppComponent {
isOnline$: Observable<boolean>;
constructor() {
this.isOnline$ = merge(
of(navigator.onLine), // Initial state
fromEvent(window, 'online').pipe(map(() => true)),
fromEvent(window, 'offline').pipe(map(() => false))
);
}
}
In your app.component.html:
html
<div *ngIf="!(isOnline$ | async)" class="offline-banner">
You are currently offline. Using cached data.
</div>
<router-outlet></router-outlet>
Step 6: Build and Test
Service workers do not work with ng serve. You must build the project and serve it using a static file server.
Build for Production:
bash
ng build
Install a static server (if you don't have one):
bash
npm install -g http-server
Serve the output folder:
bash
cd dist/advanced-pwa
http-server -p 8080 -c-1 .
(Note: -c-1 disables browser-level caching so we can test the Service Worker caching exclusively).
Step 7: Verifying in Chrome DevTools
Open Chrome and go to http://localhost:8080.
Open DevTools (F12) -> Application tab.
Service Workers: You should see "Status: Activated".
Cache Storage: Expand this on the left. You will see:
ngsw:/:...:app:cache (Your app shell)
ngsw:/:...:api-performance-catalog:cache (Your API data after you visit those pages).
Test Offline: In the "Service Workers" tab, check the "Offline" box. Refresh the page. The app should still load, and API calls configured in dataGroups should still render data