Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Build an Angular PWA with service workers and advanced caching strategies.

  1. User

    Build an Angular PWA with service workers and advanced caching strategies.

  2. Assistant
    # Prerequisites
    # 1. Install Node.js (v18+ recommended) from https://nodejs.org
    # 2. Install Angular CLI globally: npm install -g @angular/cli@latest
    # 3. Verify: ng version (should be 17+ for best PWA support)
    

    Step 1: Create a New Angular Project

    ng new angular-pwa-demo --routing --style=scss --package-manager=npm
    cd angular-pwa-demo
    

    Step 2: Add PWA Support

    This installs @angular/pwa, configures service worker, manifest, and icons.

    ng add @angular/pwa
    
    • Answer prompts: Yes to all defaults.
    • This adds:
      • src/manifest.webmanifest (app metadata for installability).
      • src/icons/ (auto-generated icons).
      • ngsw-config.json (service worker config).
      • Service worker registration in app.module.ts (via ServiceWorkerModule).

    Step 3: Build a Demo App to Showcase Caching

    We'll create a simple "Post Viewer" app:

    • Static content (offline always).
    • Fetches posts from JSONPlaceholder API (caches API responses).
    • Displays images (cache-first).
    • Works fully offline after first load.

    3.1: Update src/app/app.component.html

    <div class="container">
      <header>
        <h1>Angular PWA Demo</h1>
        <p>Service Worker + Advanced Caching: Offline-first API & Assets</p>
        <button mat-raised-button color="primary" (click)="fetchPosts()">Refresh Posts</button>
        <div class="status">
          <span>Online: {{ onlineStatus$ | async }}</span>
          <span>SW: {{ swUpdate.available | async ? 'Update Available' : 'Up-to-date' }}</span>
        </div>
      </header>
    
      <section class="posts">
        <mat-card *ngFor="let post of posts" class="post-card">
          <mat-card-header>
            <mat-card-title>{{ post.title }}</mat-card-title>
            <mat-card-subtitle>ID: {{ post.id }}</mat-card-subtitle>
          </mat-card-header>
          <mat-card-content>
            <p>{{ post.body }}</p>
            <img [src]="'https://picsum.photos/300/200?random=' + post.id" [alt]="post.title" loading="lazy">
          </mat-card-content>
        </mat-card>
      </section>
    </div>
    

    3.2: Update src/app/app.component.scss

    .container {
      padding: 20px;
      max-width: 800px;
      margin: 0 auto;
    }
    
    .status {
      margin: 10px 0;
      display: flex;
      gap: 20px;
      font-weight: bold;
    }
    
    .posts {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    .post-card {
      img {
        width: 100%;
        height: 200px;
        object-fit: cover;
      }
    }
    

    3.3: Update src/app/app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable, BehaviorSubject } from 'rxjs';
    import { map, tap } from 'rxjs/operators';
    import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
    import { OnlineStatusService } from './online-status.service';
    
    interface Post {
      id: number;
      title: string;
      body: string;
    }
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
      title = 'angular-pwa-demo';
      posts: Post[] = [];
      onlineStatus$ = this.onlineStatusService.onlineStatus$;
      swUpdate = this.swUpdate;
    
      constructor(
        private http: HttpClient,
        private swUpdate: SwUpdate,
        private onlineStatusService: OnlineStatusService
      ) {}
    
      ngOnInit() {
        this.fetchPosts();
        if (this.swUpdate.isEnabled) {
          this.swUpdate.versionUpdates.subscribe((event: VersionReadyEvent) => {
            console.log('New version available!');
            // Optional: Prompt user to reload
            window.location.reload();
          });
        }
      }
    
      fetchPosts() {
        this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts?_limit=5')
          .pipe(
            tap(posts => this.posts = posts)
          )
          .subscribe();
      }
    }
    

    3.4: Add Online Status Service (src/app/online-status.service.ts)

    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root'
    })
    export class OnlineStatusService {
      private onlineSubject = new BehaviorSubject<boolean>(navigator.onLine);
    
      onlineStatus$ = this.onlineSubject.asObservable();
    
      constructor() {
        window.addEventListener('online', () => this.onlineSubject.next(true));
        window.addEventListener('offline', () => this.onlineSubject.next(false));
      }
    }
    

    3.5: Install Angular Material (for UI)

    ng add @angular/material
    
    • Select Indigo/Pink theme, Typography, Animations: Yes.
    • Import in app.module.ts (CLI prompts).

    Update src/app/app.module.ts imports:

    import { MatCardModule } from '@angular/material/card';
    import { MatButtonModule } from '@angular/material/button';
    // Add to imports: MatCardModule, MatButtonModule
    

    3.6: Update src/index.html (add theme)

    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    

    Step 4: Configure Advanced Caching Strategies (src/ngsw-config.json)

    This is the core of advanced caching. Angular's ngsw uses Workbox under the hood.

    • Precaching: All app shell (JS/CSS/HTML/fonts) always cached.
    • Asset Groups:
      • app: Cache-first (static assets).
      • Images: Cache-first with size limit.
    • Data Groups (API):
      • api-freshness: Network-first (try net, fallback to cache >2h old? refresh).
      • Cache responses for 5min, max 50 responses.
      • Fallback to offline page if fails.
    {
      "$schema": "./node_modules/@angular/service-worker/config/schema.json",
      "index": "/index.html",
      "assetGroups": [
        {
          "name": "app",
          "installMode": "prefetch",
          "updateMode": "prefetch",
          "resources": {
            "files": [
              "/favicon.ico",
              "/index.html",
              "/*.css",
              "/*.js"
            ]
          }
        },
        {
          "name": "images",
          "installMode": "lazy",
          "updateMode": "lazy",
          "resources": {
            "files": [
              "/icons/**",
              "/*.png",
              "/*.jpg",
              "/*.svg"
            ]
          },
          "cacheConfig": {
            "strategy": "freshness",
            "maxSize": 20,
            "maxAge": "1d"
          }
        }
      ],
      "dataGroups": [
        {
          "name": "api-freshness",
          "urls": ["https://jsonplaceholder.typicode.com/posts"],
          "cacheConfig": {
            "strategy": "freshness",
            "maxSize": 50,
            "maxAge": "5m",
            "timeout": "3s"
          },
          "cacheQueryOptions": {
            "ignoreSearch": true
          }
        },
        {
          "name": "picsum-images",
          "urls": ["https://picsum.photos/**"],
          "cacheConfig": {
            "strategy": "cache-first",
            "maxSize": 100,
            "maxAge": "1d"
          }
        }
      ],
      "fallbackRule": {
        "group": "app",
        "cacheName": "fallback"
      },
      "navigationUrls": [
        "/**",
        "!/**/*.*",
        "!/**/*__*",
        "!/**/*__*/**"
      ]
    }
    

    Strategies Explained:

    StrategyBehaviorUse Case
    prefetchPre-cache on install, update on SW update.App shell (fast loads).
    cache-firstServe from cache, net only if miss.Static/images (fast, offline).
    freshness (network-first)Try net (timeout 3s), fallback cache, bg refresh.API (fresh data, offline fallback).

    Step 5: Build & Test

    Production Build

    ng build
    
    • Outputs to dist/angular-pwa-demo/.
    • Service worker auto-built.

    Serve Locally (with HTTPS simulation for PWA)

    # Install http-server globally: npm i -g http-server
    npx http-server dist/angular-pwa-demo -p 8080 -c-1 --proxy http://localhost:8080?
    

    Test Offline Caching

    1. Load app (online): Fetches API, caches images/posts.
    2. DevTools > Application > Service Workers: Check registered SW.
    3. Offline Test:
      • Network tab > Offline checkbox.
      • Refresh: App loads from cache, shows cached posts/images.
    4. Cache Inspection: Application > Cache Storage > See ngsw:... caches.

    Install as PWA

    • Chrome/Edge: Address bar > Install icon.
    • Add to home screen (mobile).

    Step 6: Advanced Tips

    • Background Sync: Add to SW for queueing failed POSTs (extend with BroadcastChannel).
    • Push Notifications: Use @angular/service-worker + FCM.
    • Custom SW: Edit src/app/sw-registration.js if needed.
    • Deploy: Firebase Hosting/Netlify (auto-HTTPS).
      # Firebase example
      npm i -g firebase-tools
      firebase init hosting
      firebase deploy
      
    • Update SW: ngsw update checks for updates.

    Your PWA is now production-ready with advanced caching: offline API fallback, image optimization, app-shell model. First load ~seconds, subsequent/offline: instant! 🚀

    For questions, ask! Source: Full project ready to copy.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.