Angular PWA: สร้าง Progressive Web App ด้วย Service Worker

#angular12 เม.ย. 2569

PWA คืออะไร

Progressive Web App (PWA) คือ web app ที่ทำงานได้เหมือน native app รองรับ offline, push notification และ install บน home screen ได้

ติดตั้ง PWA

ng add @angular/pwa

คำสั่งนี้จะสร้าง Service Worker config, App manifest และลงทะเบียน Service Worker ให้อัตโนมัติ

ตั้งค่า Cache Strategy

{
  "dataGroups": [
    {
      "name": "api-cache",
      "urls": ["/api/**"],
      "cacheConfig": {
        "strategy": "freshness",
        "maxSize": 100,
        "maxAge": "1h"
      }
    }
  ]
}

ตรวจสอบ Update

import { SwUpdate } from '@angular/service-worker';

export class AppComponent {
  constructor(private swUpdate: SwUpdate) {
    if (swUpdate.isEnabled) {
      swUpdate.versionUpdates.subscribe(event => {
        if (event.type === 'VERSION_READY') {
          if (confirm('มีเวอร์ชันใหม่ ต้องการอัปเดตไหม?')) {
            window.location.reload();
          }
        }
      });
    }
  }
}

App Manifest

{
  "name": "My Angular App",
  "short_name": "MyApp",
  "theme_color": "#1976d2",
  "display": "standalone",
  "start_url": "/"
}

Build และทดสอบ

ng build --configuration=production
npx http-server dist/my-app -p 8080

สรุป

Angular PWA ติดตั้งง่ายมากด้วย ng add ช่วยให้ app ทำงาน offline ได้และ install บน device ได้เหมือน native app ครับ