Angular Service Worker/PWA

Angular Service Worker/PWA

What is a PWA?

A Progressive Web Application (PWA) is a type of application software delivered through the web, built using HTML, CSS, and JavaScript. It is intended to work on any platform that uses a standards-compliant browser. Internally, a PWA uses service worker browser API to provide access to some native features. Also, it gives you an app-like feel. Cache storage is a really great feature that helps drastically improve page load time.

Getting Started with a PWA

I invite you to code along, as we will scaffold an application from scratch using the Angular CLI and we will configure it step-by-step to enable this feature that so far has been exclusive to native apps.

Step 1

Create a new Project using this command

ng new angular-pwa

then open in VSCode editor

cd angular-pwa && code .

Step 2

Add pwa package in project

ng add @angular/pwa

This command will create ngsw-config.json file and update in index.html, app.module.ts, angular.json, package.json .

Step 3 Add configuration in ngsw-config.json.

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js",
          "/manifest.json"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "app name",
      "urls": [
       "your api"
      ],
      "cacheConfig": {
        "strategy": "freshness",
        "maxSize": 10000,
        "maxAge": "6h",
        "timeout": "5s"
      }
    }
  ]
}
  • index->root page of app

  • assetGroups-> To cache asset which are static

  • installMode: prefetch-> When angular load it will load all files and css under prefetch
  • installMode: lazy ->It will load once you call at least once.
  • updateMode: prefetch ->When new version is deployed, it will update the data in cache.
  • dataGroups->For dynamic data cache

  • maxSize->Maximum number of response to be cache

  • maxAge->How much time hold the data in cache

This is the update once where you can cache more than one api data

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/manifest.webmanifest",
          "/*.css",
          "/*.js"
        ]
      }
    }, {
      "name": "assets",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/assets/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    },
    {
      "name": "cache",
      "installMode": "lazy",
      "updateMode": "lazy",
      "resources": {
        "urls": [
          "https://api.themoviedb.org/3/movie/now_playing?api_key=key&page=1",
          "http://localhost:3000/**",
          "https://api.themoviedb.org/3/movie/upcoming?api_key=key&page=1"


        ]
      }
    }
  ]
}

Step 3 Deploy in http server

  • Run ng build --prod command. It will create files under dist/angular-pwa folder.

  • Navigate to that folder using cd dist/angular-pwa.

  • Install Http Server(npm i -g http-server)

  • Run http server(http-server -p 8080 -c-1 )

Step 4 Open in Browser with localhost:8080.

Now click F12 to open this page and go to application tab. You can see service worker is running.

Capture.PNG

Step 5 Run in Offline

In the above fig if you select offline and refresh, you can see all data is fetching without data connection.

Step 6 Download as a Native app.

Capture.PNG

You can see a download option in your url bar. If you click it will download as a app.

Step 7 Update Cache

After you deploy new version it show update in cache also . For this you have write code in app.component.ts.

  • swUpdate->It will check weather new version is available or not.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

})

export class AppComponent implements OnInit, OnDestroy {

  constructor(

    private swUpdate: SwUpdate, private snackBar: MatSnackBar,
  ) {

  }
  ngOnInit() {


    if (this.swUpdate.isEnabled) {
      this.swUpdate.available.subscribe(() => {
        const message = 'New version available. Update to new Version ?';
        const action = 'UPDATE';

        console.log(message);

        const snackbarRef = this.snackBar.open(message, action);
        snackbarRef.onAction().subscribe(() => {
          window.location.reload();
        });
      });
    }
  }



}

Conclucion

I hope you have understood how you can install and configure PWA in an Angular application.