At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Learn How: Create A PWA with Service Workers in Angular

  • By Manigandan
  • November 12, 2019
  • 8721 Views
The Interest for Progressive Web Apps is increasing rapidly. PWA is acknowledged by huge companies for front end development. The concept is evolving and growing faster than expected. In this post, you can learn how to create a

Progressive Web App with Service Workers in Angular.

Let’s get started with a basic outline of PWA and Service Workers.

What is PWA?

Progressive Web Apps (PWA) are a mobile website similar to native apps. It is a modern website that gives the users app-like experience while accessing website content. You can build fast, strong and reliable web apps that will engage more audiences to the website. You can also add the website as a shortcut on the mobile screen for instant access.

What are Service Workers?

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. It includes features like push notifications and background sync. In the future, service workers might support things like periodic sync or geofencing. The core feature is the ability to intercept and handle network requests, including programmatically managing a cache of responses.
-Matt Gunt, Developers.google.com

How setup service workers in existing or new angular application?

Before you start integration the PWA in the angular application you have check your application is already enabled PWA or Not using chrome browser.

Step 1: Open your application in the chrome browser. In my case, http://localhost:8080
Step 2: Open to inspect the window and select the Audits tab.

PWA service workers in Angular
Choose Device & audits type and click Run audit button. It’s will show the audit detail result as shown in the below image.
A PWA with Service Workers in Angular
The audit result will be displayed that there is no PWA at present. So, now I am going to implement the Progressive Web App to work. Navigate to install your application, install path and add the below command.

ng add @angular/pwa

Once executed the above command, you will get the manifest link in index.html file and automatically added ngsw-config.json file in the root directory.
A PWA with Service Workers in Angular
Next, To enable the service worker & ngswConfigPath in angular.json file in under configurations Objects. Below config added automatically. If not you have to add it manually.

 "serviceWorker": true,
       "ngswConfigPath": "ngsw-config.json"

To add the service worker module in app.module files as below.

import { BrowserModule } from '@angular/platform-browser';
      import { NgModule } from '@angular/core';
      import { AppRoutingModule } from './app-routing.module';
      import { AppComponent } from './app.component';
      import { ServiceWorkerModule } from '@angular/service-worker';
      import { environment } from '../environments/environment';
      @NgModule({
        declarations: [
          AppComponent
        ],
        imports: [
          BrowserModule,
          AppRoutingModule,
          ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
The ngsw-worker.js file will be available in the production build. Finally, after you verify all the static files add ngsw-config.json. In this file used to add the static files like .js, .css, images, font files, and external URLs.
{
        "$schema": "./node_modules/@angular/service-worker/config/schema.json",
        "index": "/index.html",
        "assetGroups": [
          {
            "name": "app",
            "installMode": "prefetch",
            "resources": {
              "files": [
                "/favicon.ico",
                "/index.html",
                "/manifest.webmanifest",
                "/*.css",
                "/*.js"
              ]
            }
          }, {
            "name": "assets",
            "installMode": "lazy",
            "updateMode": "prefetch",
            "resources": {
              "files": [
                "/assets/**",
                "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
              ]
            }
          }
        ]
      }

Now, it is ready to check with PWA enabled application. The PWA has to work in the production build. This following comment used to create a production build.

ng build --prod

Once you create the production build, you will see the ngsw-worker.js file in the build.

How to run the production build in the local environment?

Step 1:The npm package http-server is used to run the lightweight node server. The http-server package is installed globally, you can easily install it using the below command.

sudo npm install -g http-server
Step 2:Once installed, run the server using the following command.

http-server -p 8080 <buid file directory>

A PWA with Service Workers in Angular
Check if the PWA is enabled using the above-mentioned steps. The audits result will look like this.
PWD-enable
The PWA service worker caches the static files in the local browser, so the application won’t break even if there is no internet connection.

How to catch the external URL using service workers?

In this case, I am using google font. The URL is added to the index.html file.

<link rel="manifest" href="manifest.webmanifest">
          <link
        href="https://fonts.googleapis.com/css?family=Supermercado+One&display=swap" rel="stylesheet">
Step 1: Firstly, check if the font file is cached in PWA.
Disconnect the internet and check if the font is loading in your application. You can see the network tab in the inspect window in Chrome.
PWA with Service Workers in Angular
Step 2:Add the following code to an ngsw-config.json file in under assetGroups.

"urls": [
                  "https://fonts.googleapis.com/css?family=Supermercado+One&display=swap"
                ]

Once you add the above code, run the production build and verify the application working in both online & offline. Now the file is catched from the service worker.

How to catch the service API using service workers?

Usually, application service API works with the Internet connection. Only if the browser works well without the internet, you can catch the service API in service workers.

Step 1: Use dataGroups to catch the service APIs. dataGroups structure as follows,

dataGroups : {
            name: string,
              urls: string[],
              version?: number;
              cacheConfig: {
                maxSize: number,
                maxAge: string,
                timeout?: string,
                strategy?: 'freshness' | 'performance';
              };
            }

Name is used to uniquely identifies for each service APIs. URLs are a collection array string. It’s used to specify the catching service APIs URLs. Version is used to maintain the API catching versions in the application. cache config is used to match requests that will be cached based on below params,

maxSize: number,
            maxAge: string,
            timeout?: string,
            strategy?: 'freshness' | 'performance';
Step 2:catch the open source API endpoint.
Endpoint: https://jsonplaceholder.typicode.com/todos

"dataGroups": [
                {
                  "name": "todos",
                  "urls": [
                    "https://jsonplaceholder.typicode.com/todos"
                  ],
                  "cacheConfig": {
                    "maxSize": 5,
                    "maxAge": "6h",
                    "timeout": "10s",
                    "strategy": "freshness"
                  }
                }
              ]
Step 3:Once the configuration is done. Run the application in production mode. Now, the application will run both online and workout online.

PWA with Service Workers in Angular

Over to You

I hope, this tutorial helps. From setting up the installation to Working with production build, and Catching service API with service workers. Make sure that your PWA is working well as a static page both online and offline. With this guide, you must have understood how you can create a PWA with the help of Service Workers in Angular with the simple instruction used on this tutorial.
And also you can try working with the same commands and methods used in this blog. It is available HERE!
Looking for more Angular Tutorials? Visit our blog and Subscribe for exclusive & latest articles on development technologies.
If you lack clarity or have doubts, suggestions on this blog, feel free to tell us in the comment section below.
Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Manigandan

An ideal Full Stack Developer, having around 5+ years of experience in web development arena, expertise in AngularJS, Nodejs, PHP and also scoring 6 years of experience in Networking & Window servers. A perfect all-rounder has fondness to play diverse role. he always strives to match perfection and likely remains the best in whatever role he takes.