Angular Service Workers Usage Guide

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

In this article, we can see what is service worker and how it can be used by connecting to public API and if this app goes offline, how still information can be displayed.

Service worker is a network proxy which acts between the UI client and back-end server to do cache, sync assets when comes back to online, push notifications and intercept the network requests. It runs in worker context and does not have DOM access as it runs in a separate thread.

Angular integrated browser's service worker, so a developer makes their application to use the functionalities in their application by a declarative configuration file (ngsw-config.json). It can also enabled in angular project easy by angular cli tool. Refer our previous article, to know basics of Angular and how to install and create angular sample application.

Once the project "my-app" is created, service worker can be enabled by following commands

   cd my-app
   ng add @angular/pwa

After executing the command, it adds the Angular PWA dependency, imports service workers which is similar to any module adding to Angular project. It does two main things

  1. Includes manifest.json file - information about the web application
  2. Create ngsw-config.json service worker configuration file

Manifest.json file contains information about the web application needed to be downloaded and presented as standalone application in the device. It contains the details like service worker, name, orientation etc.

ngsw-config.json file is service worker configuration file which specifies files and data URLs, the Angular service worker should cache and how it should update the cached files and data. It will be processed when we build for production "ng build --prod".

After the application production build is done, run the following commands

 npm install -g http-server
 http-server -p 8090 -c ./dist/my-app

Now when we open the application in chrome browser, developer console (F12) --> applications tab --> service worker sub section, shows the service worker running. If it is not running, please check whether you are using recent chrome version or run audit to check the pwa score.

Lets take public breaking news API, which is real time news feed and declare it in application component file.

File: app.component.ts

  private newsurl = "";

Then the data can be fetched using HTTP client, for the public API, we need to pass host and API key. Refer the API documentation for more information.

  constructor(private httpclient: HttpClient) {}

  ngOnInit() {
      this.isCachedData = !window.navigator.onLine;
      console.log("assigning value --"+this.isCachedData);
      const httpOptions = {
          headers: new HttpHeaders({
          'X-RapidAPI-Host': '',
          'X-RapidAPI-Key': '<YOUR-API-KEY>'
  console.log("ng on initialization");
  this.httpclient.get(this.newsurl, httpOptions)
          .subscribe((resp) => {
                this.newslist = resp['Data'];
                this.isLoading = false;
   }, (err) => {

This API returns list of news, each news item will have the title, duration and source by which we can display a UI dashboard view. As it is an external API, till elapsed time of rendering the news, we can show the loading message. This is controlled by "isLoading" flag.

File: app.component.html

   <div class="header"> 
        <h1 class="whitetext"> Breaking News </h1>
   <div class="newsbody">
       <div *ngIf="isLoading">
       <h3 style="text-align: center;">Loading latest news.. </h3>
    <div *ngIf="!isLoading">
      <li class="newsitem" *ngFor="let news of newslist">
            <p class="newsheading">
               <span class="newsduration">{{news.Duration}}</span>
          <label class="sourcetext">Source: {{news.SourceName}}</label>

CSS to have a dashboard view which can be done using the below styles.

File: app.component.css

 h1 {
   color: #369;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 250%;

 .header {
   position: fixed;
   left: 0px;
   width: 100%;

 .whitetext {
   color: white;

 .newsbody {
   position: relative;
   top: 150px;

 .newsitem {
   border-radius: 5px;
   list-style-type: none;
   background-color: #f6e5d6;
   width: 80%;
   padding: 20px;
   margin: 5px; margin-left: 120px;

 .centertext {
   text-align: center;

 .warningtext {
   color: red;

 .sourcetext {
   float: right;
   font-size: 14px;
   font-weight: 200;
   color: grey;

 .newsheading {
   font-size: 16px;

 .newsduration {
   font-weight: normal;

 Now build the angular project and open the application it looks like below.

Then go to developer console and then to network tab and make it offline. Screen shows only with heading, but news are missing. So warning message with last fetched news will be good to engage the user with screen.

So the service worker configuration has to be changed to cache the API information. This configuration can be added in ngsw-config.json file.

 "dataGroups": [
  "name": "breaking-news-api",
   "urls" : [
   "cacheConfig": {
    "strategy": "freshness",
    "maxSize": 10000,
    "maxAge": "1h",
    "timeout": "50s"

So it will cache the news for 1 hour (can be reduced if you wish) and can hold max entries of 10000, freshness strategy it hold last fetch news till application came to connect online.

While showing information, we need to inform the user with caution saying the cached news. so the below can be added in app.component.html.

  <div *ngIf="isCachedData">
      <p class="centertext warningtext">Showing cached data as not able to connect to the network</p>

Now build the project as production build and open the app. If we go offline, the application shows the news with warning message as shown.

We can now make this as an app and store in our desktop so whenever we want it just open the application. Just go to the chrome menu, where we could see install my-app, click and confirm. Then it opens my-app exclusive window with title of it. It also works as mobile app in mobile device. There will be shortcut available in the desktop also.

Service workers works best in production environment only with HTTPS. so to host as HTTPS, use the following command.

To run in HTTPS mode, we need a private key and certificate to start the server. Refer the article to know how to generate self signed certificate using OpenSSL. If you want free and public certificate, you can create certificate from LetsEncrypt

   http-server -S -C generatedcert.crt -K rsaprivatekey.pem -p 8090 -c-1 ./dist/my-app/

Angular provides more services for using service workers which can be referred in their application.


Source link :


Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More

All About Multi-Provider Feature of Angular Version 2.0

  • angular dependency-injection multi-providers

The newly introduced concept of dependency injection in Angular version 2.0 makes it an attractive front-end technology all because of one amazing feature called 'Multi-Providers'. In general, it allows the users to attach certain operations by themselves and a few plugin custom functionality which is not required in our mobile app use case.

Read More

Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Read More

Ngnix - High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy

  • load-balancer proxy-server web-server

Nginx is a High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy server. It can also be used as mail proxy server and a generic TCP/UDP proxy server. Nginx claims to be more efficient and faster in the Web space compared to the other web servers. This can be evident with the architecture which is based on asynchronous event-driven approach. The event driven architecture enables to scale to hundreds / thousands of concurrent connections.

Read More

JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More

Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More

COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More

Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More

Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More

ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More

React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More

Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More

Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More

RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More

RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More

Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More

RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More

Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.