Skip to content
TheChatArchiveThe Chat Archive
ClaudeClaude Haiku 4.5· anthropicHugging Face Frontier Reasoning Traces

Build an Angular PWA with version control where the ServiceWorkerModule doesn't…

  1. User

    Build an Angular PWA with version control where the ServiceWorkerModule doesn't auto-update. Listen to SwUpdate.available and show a toast saying "New version available. Click to Reload." Only activate the new service worker when clicked.

  2. Claude Assistant

    The user wants me to build an Angular PWA with version control that:

    1. Disables auto-update of the ServiceWorkerModule
    2. Listens to SwUpdate.available event
    3. Shows a toast message asking to reload
    4. Only activates the new service worker when the user clicks to reload

    Let me create a comprehensive solution with:

    1. Angular app setup with ServiceWorkerModule
    2. A custom service to handle service worker updates
    3. A component/notification to display the toast
    4. Proper configuration files

    Here's what I need to include:

    1. app.config.ts or app.module.ts - Configure Angular for PWA with ServiceWorkerModule
    2. environment.config.ts - Service worker configuration to disable auto-update
    3. update.service.ts - Handle SwUpdate events
    4. app.component.ts - Listen to updates and show toast
    5. A toast/notification component
    6. ngsw-config.json - Service worker configuration
    7. package.json - required dependencies
    8. Instructions for building and testing

    Let me create a complete solution:

    Angular PWA with Manual Service Worker Updates

    I'll create a complete Angular PWA with version control, toast notifications, and manual update activation.

    Project Structure

    src/
    ├── app/
    │   ├── services/
    │   │   └── update.service.ts
    │   ├── components/
    │   │   └── update-toast/
    │   │       ├── update-toast.component.ts
    │   │       ├── update-toast.component.html
    │   │       └── update-toast.component.scss
    │   ├── app.config.ts
    │   ├── app.component.ts
    │   └── app.component.html
    ├── ngsw-config.json
    ├── manifest.webmanifest
    └── main.ts
    

    1. Update Service (src/app/services/update.service.ts)

    import { Injectable, inject } from '@angular/core';
    import { SwUpdate, VersionEvent } from '@angular/service-worker';
    import { BehaviorSubject, Observable, interval } from 'rxjs';
    import { filter, map } from 'rxjs/operators';
    
    export interface UpdateInfo {
      available: boolean;
      version: string;
    }
    
    @Injectable({
      providedIn: 'root',
    })
    export class UpdateService {
      private swUpdate = inject(SwUpdate);
    
      private updateAvailable$ = new BehaviorSubject<UpdateInfo>({
        available: false,
        version: '',
      });
    
      constructor() {
        this.initializeUpdateListener();
      }
    
      private initializeUpdateListener(): void {
        // Check for updates every 6 hours
        interval(6 * 60 * 60 * 1000).subscribe(() => {
          this.checkForUpdates();
        });
    
        // Listen to update availability
        this.swUpdate.versionUpdates
          .pipe(
            filter(
              (evt): evt is VersionEvent =>
                evt.type === 'VERSION_READY' || evt.type === 'VERSION_DETECTED'
            )
          )
          .subscribe((evt) => {
            console.log('Version event:', evt.type, evt.latestVersion?.hash);
    
            if (evt.type === 'VERSION_READY') {
              // New version is ready but not activated
              const newVersion = evt.latestVersion?.hash || 'unknown';
              this.updateAvailable$.next({
                available: true,
                version: newVersion,
              });
            }
          });
      }
    
      // Manual check for updates
      checkForUpdates(): void {
        if (this.swUpdate.isEnabled) {
          this.swUpdate.checkForUpdate().catch((err) => {
            console.error('Error checking for updates:', err);
          });
        }
      }
    
      // Get observable of update availability
      getUpdateAvailable$(): Observable<UpdateInfo> {
        return this.updateAvailable$.asObservable();
      }
    
      // Activate new version and reload
      activateUpdate(): void {
        if (this.swUpdate.isEnabled) {
          this.swUpdate.activateUpdate().then(() => {
            window.location.reload();
          });
        }
      }
    
      // Dismiss update notification
      dismissUpdate(): void {
        this.updateAvailable$.next({
          available: false,
          version: '',
        });
      }
    }
    

    2. Update Toast Component

    src/app/components/update-toast/update-toast.component.ts

    import { Component, inject, OnInit, OnDestroy } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { trigger, transition, style, animate } from '@angular/animations';
    import { UpdateService, UpdateInfo } from '../../services/update.service';
    import { Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    
    @Component({
      selector: 'app-update-toast',
      standalone: true,
      imports: [CommonModule],
      animations: [
        trigger('slideIn', [
          transition(':enter', [
            style({ transform: 'translateY(100%)', opacity: 0 }),
            animate(
              '300ms ease-out',
              style({ transform: 'translateY(0)', opacity: 1 })
            ),
          ]),
          transition(':leave', [
            animate(
              '300ms ease-in',
              style({ transform: 'translateY(100%)', opacity: 0 })
            ),
          ]),
        ]),
      ],
      template: `
        <div
          class="toast-container"
          *ngIf="updateInfo.available"
          [@slideIn]
        >
          <div class="toast-content">
            <div class="toast-message">
              <svg class="toast-icon" viewBox="0 0 24 24">
                <path
                  d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"
                />
              </svg>
              <span class="message-text">
                <strong>New version available!</strong>
                <br />
                Click to reload and get the latest updates.
              </span>
            </div>
    
            <div class="toast-actions">
              <button
                class="btn btn-primary"
                (click)="onReload()"
              >
                Reload
              </button>
              <button
                class="btn btn-secondary"
                (click)="onDismiss()"
              >
                Dismiss
              </button>
            </div>
          </div>
          <div
            class="progress-bar"
            [style.animation]="'progress 8s linear forwards'"
          ></div>
        </div>
      `,
      styles: [`
        .toast-container {
          position: fixed;
          bottom: 20px;
          right: 20px;
          max-width: 400px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 12px;
          box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
          overflow: hidden;
          z-index: 9999;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
            Ubuntu, Cantarell, sans-serif;
        }
    
        .toast-content {
          padding: 20px;
          color: white;
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 20px;
        }
    
        .toast-message {
          display: flex;
          align-items: center;
          gap: 15px;
          flex: 1;
        }
    
        .toast-icon {
          width: 24px;
          height: 24px;
          fill: white;
          flex-shrink: 0;
          animation: pulse 2s ease-in-out infinite;
        }
    
        @keyframes pulse {
          0%, 100% {
            opacity: 1;
          }
          50% {
            opacity: 0.7;
          }
        }
    
        .message-text {
          font-size: 14px;
          line-height: 1.4;
        }
    
        strong {
          display: block;
          margin-bottom: 4px;
          font-size: 15px;
        }
    
        .toast-actions {
          display: flex;
          gap: 10px;
          flex-shrink: 0;
        }
    
        .btn {
          padding: 8px 16px;
          border: none;
          border-radius: 6px;
          font-size: 13px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
    
        .btn-primary {
          background: white;
          color: #667eea;
        }
    
        .btn-primary:hover {
          transform: scale(1.05);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }
    
        .btn-secondary {
          background: rgba(255, 255, 255, 0.2);
          color: white;
          border: 1px solid rgba(255, 255, 255, 0.4);
        }
    
        .btn-secondary:hover {
          background: rgba(255, 255, 255, 0.3);
        }
    
        .btn:active {
          transform: scale(0.98);
        }
    
        .progress-bar {
          height: 3px;
          background: rgba(255, 255, 255, 0.5);
        }
    
        @keyframes progress {
          from {
            width: 100%;
          }
          to {
            width: 0;
          }
        }
    
        @media (max-width: 500px) {
          .toast-container {
            bottom: 10px;
            right: 10px;
            left: 10px;
            max-width: none;
          }
    
          .toast-content {
            flex-direction: column;
            align-items: flex-start;
          }
    
          .toast-actions {
            width: 100%;
          }
    
          .btn {
            flex: 1;
          }
        }
      `],
    })
    export class UpdateToastComponent implements OnInit, OnDestroy {
      private updateService = inject(UpdateService);
      private destroy$ = new Subject<void>();
    
      updateInfo: UpdateInfo = {
        available: false,
        version: '',
      };
    
      ngOnInit(): void {
        this.updateService
          .getUpdateAvailable$()
          .pipe(takeUntil(this.destroy$))
          .subscribe((info) => {
            this.updateInfo = info;
          });
      }
    
      onReload(): void {
        this.updateService.activateUpdate();
      }
    
      onDismiss(): void {
        this.updateService.dismissUpdate();
      }
    
      ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
      }
    }
    

    3. App Configuration (src/app/app.config.ts)

    For Angular 17+ with standalone:

    import { ApplicationConfig, importProvidersFrom } from '@angular/core';
    import { provideRouter } from '@angular/router';
    import { provideAnimations } from '@angular/platform-browser/animations';
    import { ServiceWorkerModule } from '@angular/service-worker';
    import { environment } from '../environments/environment';
    import { routes } from './app.routes';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideRouter(routes),
        provideAnimations(),
        importProvidersFrom(
          ServiceWorkerModule.register('ngsw-worker.js', {
            enabled: environment.production,
            // IMPORTANT: Set registrationStrategy to disable auto-registration
            registrationStrategy: 'registerWhenStable:30000',
          })
        ),
      ],
    };
    

    For Angular 16 and earlier (module-based):

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { ServiceWorkerModule } from '@angular/service-worker';
    import { environment } from '../environments/environment';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        BrowserAnimationsModule,
        ServiceWorkerModule.register('ngsw-worker.js', {
          enabled: environment.production,
          registrationStrategy: 'registerWhenStable:30000',
        }),
      ],
      bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    4. App Component (src/app/app.component.ts)

    import { Component, inject } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { UpdateToastComponent } from './components/update-toast/update-toast.component';
    import { UpdateService } from './services/update.service';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, UpdateToastComponent],
      template: `
        <div class="app-container">
          <header class="app-header">
            <h1>Angular PWA with Version Control</h1>
            <p class="version-info">{{ versionInfo }}</p>
          </header>
    
          <main class="app-content">
            <section class="feature-section">
              <h2>Features</h2>
              <ul>
                <li>✅ Service Worker with manual update control</li>
                <li>✅ Toast notification for new versions</li>
                <li>✅ One-click reload activation</li>
                <li>✅ Progressive Web App (PWA)</li>
                <li>✅ Offline support</li>
              </ul>
            </section>
    
            <section class="info-section">
              <h2>How It Works</h2>
              <ol>
                <li>Service Worker checks for updates periodically</li>
                <li>When new version is available, toast appears</li>
                <li>Click "Reload" to activate new version</li>
                <li>Browser reloads with latest assets</li>
              </ol>
            </section>
    
            <section class="action-section">
              <button (click)="checkUpdatesManually()" class="check-updates-btn">
                🔄 Check for Updates Manually
              </button>
              <p class="info-text">
                The app checks for updates automatically every 6 hours.
              </p>
            </section>
          </main>
    
          <app-update-toast></app-update-toast>
        </div>
      `,
      styles: [`
        .app-container {
          min-height: 100vh;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #333;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
            Oxygen, Ubuntu, Cantarell, sans-serif;
        }
    
        .app-header {
          background: rgba(255, 255, 255, 0.95);
          padding: 40px 20px;
          text-align: center;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
          border-bottom: 3px solid #667eea;
        }
    
        .app-header h1 {
          margin: 0 0 10px;
          font-size: 32px;
          color: #333;
        }
    
        .version-info {
          margin: 0;
          font-size: 14px;
          color: #666;
          font-style: italic;
        }
    
        .app-content {
          max-width: 900px;
          margin: 0 auto;
          padding: 40px 20px;
        }
    
        section {
          background: white;
          border-radius: 12px;
          padding: 30px;
          margin-bottom: 20px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    
          h2 {
            color: #667eea;
            margin-top: 0;
            margin-bottom: 20px;
            font-size: 24px;
          }
        }
    
        .feature-section ul {
          list-style: none;
          padding: 0;
          margin: 0;
        }
    
        .feature-section li {
          padding: 12px 0;
          font-size: 16px;
          color: #555;
          border-bottom: 1px solid #eee;
    
          &:last-child {
            border-bottom: none;
          }
        }
    
        .info-section ol {
          padding-left: 20px;
          color: #555;
        }
    
        .info-section li {
          margin-bottom: 12px;
          font-size: 16px;
        }
    
        .action-section {
          text-align: center;
        }
    
        .check-updates-btn {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border: none;
          padding: 14px 32px;
          border-radius: 8px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
          }
    
          &:active {
            transform: translateY(0);
          }
        }
    
        .info-text {
          margin-top: 15px;
          font-size: 14px;
          color: #999;
          font-style: italic;
        }
    
        @media (max-width: 600px) {
          .app-header {
            padding: 30px 15px;
          }
    
          .app-header h1 {
            font-size: 24px;
          }
    
          section {
            padding: 20px;
            margin-bottom: 15px;
          }
    
          .app-content {
            padding: 20px 15px;
          }
        }
      `],
    })
    export class AppComponent {
      private updateService = inject(UpdateService);
    
      versionInfo = `Version: ${new Date().getTime()}`;
    
      checkUpdatesManually(): void {
        this.updateService.checkForUpdates();
      }
    }
    

    5. Service Worker 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": "lazy",
          "resources": {
            "files": [
              "/assets/**",
              "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
            ]
          }
        }
      ],
      "dataGroups": [
        {
          "name": "api-cache",
          "urls": [
            "/api/**"
          ],
          "cacheConfig": {
            "strategy": "performance",
            "maxSize": 100,
            "maxAge": "24h"
          }
        }
      ]
    }
    

    6. Web App Manifest (src/manifest.webmanifest)

    {
      "name": "Angular PWA - Version Control",
      "short_name": "PWA Update Demo",
      "description": "Angular PWA with manual service worker updates",
      "start_url": "/",
      "display": "standalone",
      "background_color": "#ffffff",
      "theme_color": "#667eea",
      "orientation": "portrait-primary",
      "icons": [
        {
          "src": "/assets/icon-192.png",
          "sizes": "192x192",
          "type": "image/png",
          "purpose": "any"
        },
        {
          "src": "/assets/icon-512.png",
          "sizes": "512x512",
          "type": "image/png",
          "purpose": "any"
        },
        {
          "src": "/assets/icon-maskable-192.png",
          "sizes": "192x192",
          "type": "image/png",
          "purpose": "maskable"
        },
        {
          "src": "/assets/icon-maskable-512.png",
          "sizes": "512x512",
          "type": "image/png",
          "purpose": "maskable"
        }
      ]
    }
    

    7. Environment Configuration (src/environments/environment.ts)

    export const environment = {
      production: false,
      apiUrl: 'http://localhost:4200',
    };
    
    export const environmentProduction = {
      production: true,
      apiUrl: 'https://your-app.com',
    };
    

    8. Main Entry Point (src/main.ts)

    import { bootstrapApplication } from '@angular/platform-browser';
    import { appConfig } from './app/app.config';
    import { AppComponent } from './app/app.component';
    
    bootstrapApplication(AppComponent, appConfig).catch((err) =>
      console.error(err)
    );
    

    9. Package.json Scripts

    {
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "build:pwa": "ng build --configuration production",
        "serve:pwa": "npx http-server dist/app-name -p 8080 -g",
        "test": "ng test",
        "lint": "ng lint",
        "sw:check": "sw-precache --root=dist --static-file-globs='dist/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'"
      },
      "dependencies": {
        "@angular/animations": "^17.0.0",
        "@angular/common": "^17.0.0",
        "@angular/compiler": "^17.0.0",
        "@angular/core": "^17.0.0",
        "@angular/forms": "^17.0.0",
        "@angular/platform-browser": "^17.0.0",
        "@angular/platform-browser-dynamic": "^17.0.0",
        "@angular/router": "^17.0.0",
        "@angular/service-worker": "^17.0.0",
        "rxjs": "^7.8.0",
        "tslib": "^2.6.0",
        "zone.js": "^0.14.0"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "^17.0.0",
        "@angular/cli": "^17.0.0",
        "@angular/compiler-cli": "^17.0.0",
        "typescript": "~5.2.0"
      }
    }
    

    Building and Testing

    Development Mode

    npm start
    # Service Worker not registered in dev mode
    

    Production Build

    npm run build:pwa
    

    Test with Local Server

    npm run build:pwa
    npm run serve:pwa
    # Visit http://localhost:8080
    

    Testing Update Flow

    1. Build and deploy version 1

      npm run build:pwa
      npm run serve:pwa
      
    2. Verify SW is registered

      • Open DevTools → Application → Service Workers
      • Should show "Activated and running"
    3. Make a small change and rebuild

      • Update text in app.component.ts
      • Run build again
    4. Hard refresh in another tab while keeping first tab open

      • New version detected
      • Toast appears
      • Click "Reload" to activate

    Key Features

    ✅ Manual Update Control - No auto-reload ✅ Toast Notification - Beautiful, animated UI ✅ Periodic Checking - Checks every 6 hours ✅ Manual Check Button - User can check anytime ✅ Graceful Dismissal - Toast can be dismissed ✅ Responsive Design - Works on all devices ✅ TypeScript - Fully typed ✅ Standalone Components - Modern Angular 17+ ✅ Animations - Smooth transitions ✅ Offline Support - PWA ready

    This solution provides complete control over service worker updates with a great UX!

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