Search

Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

Angular Service Workers Usage Guide

  • Share this:

post-title

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

DevGroves Technologies

About author
DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.