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 = "https://myallies-breaking-news-v1.p.rapidapi.com/GetTopNews";


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': 'myallies-breaking-news-v1.p.rapidapi.com',
          'X-RapidAPI-Key': '<YOUR-API-KEY>'
     })
  };
  console.log("ng on initialization");
  this.httpclient.get(this.newsurl, httpOptions)
          .subscribe((resp) => {
                console.log(resp['Data']);
                this.newslist = resp['Data'];
                this.isLoading = false;
   }, (err) => {
      console.log(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>
   <div class="newsbody">
       <div *ngIf="isLoading">
       <h3 style="text-align: center;">Loading latest news.. </h3>
    </div>
    <div *ngIf="!isLoading">
    <ul>
      <li class="newsitem" *ngFor="let news of newslist">
            <p class="newsheading">
               {{news.MainTitle}}
               <span class="newsduration">{{news.Duration}}</span>
           </p>
          <label class="sourcetext">Source: {{news.SourceName}}</label>
         <br/>
      </li>
    </ul>
   </div>
  </div>


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 {
   text-align:center;
   background-color:#8b5a2b;
   position: fixed;
   top:0px;
   left: 0px;
   width: 100%;
 }

 .whitetext {
   color: white;
 }

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

 .newsitem {
   background-color:lightgrey;
   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-weight:bold;
   font-size: 16px;
 }

 .newsduration {
   float:right;
   font-size:12px;
   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" : [
     "https://myallies-breaking-news-v1.p.rapidapi.com/GetTopNews"
   ],
   "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>
  </div>

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.

References:

Source link : https://github.com/nagappan080810/angular7projects/tree/master/my-app

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

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

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


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


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


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


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

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


10 Free services for your Website / Blog. Just plug it.

  • free website blog free-service free-resources

Each website / blog delivers useful content or service to its users. But website themselves requires some service to monitor and increase its presence. Here are few free services which could be used by Website / Blog. This will be very much helpful for small business owners.

Read More


Enhancing The Experience With Android TV: Briefly About One Developer's Impressions

  • android android-tv

In my software development career, I have always been attracted to new technologies and innovative solutions. Project by project, I have been exploring something new, discovering and implementing different approaches and trying new solutions. When Android TV showed up, I set a new personal goal. I described my impressions and the overall opinion on the application development for Android TV right here. Hope you will find it useful and interesting.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


ONLYOFFICE Document Server, an online office app for Nextcloud and ownCloud

  • office office-suite word spreadsheet

ONLYOFFICE Document Server is a free collaborative online office suite including viewers and editors for texts, spreadsheets and presentations, fully compatible with Office Open XML formats (.docx, .xlsx, .pptx). This article provides you the overview of ONLYOFFICE Document Server, its features, installation and integration with Nextcloud and ownCloud.

Read More


Europe Copyright reform may affect Open Source Ecosystem

  • copyright europe save-code-share

Europe is planning to bring in new copyright law, which would require code sharing sites to monitor copyright content to avoid potential copyright infringement. The proposed Article 13 of the EU Copyright Directive targets every online service that allows its users to upload and share content with each other, including code hosting platforms.

Read More