NashTech Insights

Let’s Deep Down To Angular Service Workers & PWA (Part-1)

Alka Vats
Alka Vats
Table of Contents
service

In this blog, we will learn about the angular services workers. What actually are angular service workers? How we can implement it in our angular applications? What is PWA? And last, we will see an example.
In the next series on this topic, we will learn about Service worker communication, Service worker notifications and etc.
If you want to learn about new features of angular you can refer here.
So let’s start and understand what are exactly angular service workers?

Introduction

Angular Service Workers and Progressive Web Apps (PWA) are powerful tools that can help improve the performance and user experience of web applications. In this blog post, we will explore the benefits of using Angular Service Workers and PWA, and how to implement them in your Angular application with an example.
You can refer here if you want to learn more about it.

What are Angular Service Workers?

Angular Service Workers are scripts that run in the background of your application, allowing it to work offline and provide a more seamless user experience. They are built on top of the Web Workers API and are used to cache assets, provide push notifications, and handle background synchronization.

What are Progressive Web Apps?

Progressive Web Apps (PWA) are web applications that are designed to provide a native-like experience to users. They are fast, reliable, and work offline, making them ideal for mobile devices. PWAs are built using web technologies such as HTML, CSS, and JavaScript, and can be installed on a user’s device like a native app.

Benefits of Angular Service Workers & PWA

There are several benefits to using Angular Service Workers and PWA in your web application:

  • Improved performance: Service Workers can cache your application’s assets, allowing it to load faster and reducing the load on your server. PWAs are designed to be fast and responsive, providing a seamless user experience.
  • Offline support: Service Workers can cache your application’s assets, allowing it to work offline. This is especially important for mobile devices, where network connectivity can be unreliable.
  • Push notifications: Service Workers can handle push notifications, allowing you to send notifications to your users even when they are not actively using your application.
  • Improved user experience: PWAs are designed to provide a native-like experience to users, with features such as home screen icons, full-screen mode, and immersive experiences.

Implementing Angular Service Workers & PWA

Implementing Angular Service Workers and PWA in your application is relatively straightforward. Here are the basic steps:

Step 1: Create a new Angular project

Create a new Angular project using the Angular CLI. Open a terminal window and run the following command:

ng new my-app --routing --style=scss --skipTests=true

This will create a new Angular project with routing, SCSS styling, and without unit tests.

Step 2: Add the @angular/service-worker package

Install the @angular/service-worker package using npm. Run the following command in your terminal window:

npm install @angular/service-worker --save

This will install the @angular/service-worker package and add it to your project’s package.json file.

Step 3: Configure the Service Worker

Configure the Service Worker in your application’s app.module.ts file. Add the following code to the file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ServiceWorkerModule } from '@angular/service-worker';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
    }),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

This code imports the ServiceWorkerModule from the @angular/service-worker package and registers the ngsw-worker.js file as the Service Worker for your application. The enabled property is set to, environment.production, which means that the Service Worker will only be enabled in production mode.

Step 4: Build your application

Build your application using the ng build –prod command. Open a terminal window and run the following command:

ng build --prod

This will build your application in production mode and create a dist folder in your project directory.

Step 5: Deploy your application

Deploy your application to a web server that supports HTTPS. You can use a service like Firebase Hosting, Netlify, or GitHub Pages to host your application.

Step 6: Test your application

Test your application to ensure that it is working as expected. Open your application in a web browser and verify that it is working offline. You can also test push notifications by sending a test notification to your application.

Example

Let’s create a simple example to demonstrate how Angular Service Workers and PWA can be used in an application. We will create a weather app that displays the current weather for a user’s location.

Step 1: Create a new Angular project

Create a new Angular project using the Angular CLI. Open a terminal window and run the following command:

ng new weather-app --routing --style=scss --skipTests=true

This will create a new Angular project with routing, SCSS styling, and without unit tests.

Step 2: Add the @angular/service-worker package

Install the @angular/service-worker package using npm. Run the following command in your terminal window:

npm install @angular/service-worker --save

This will install the @angular/service-worker package and add it to your project’s package.json file.

Step 3: Configure the Service Worker

Configure the Service Worker in your application’s app.module.ts file. Add the following code to the file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ServiceWorkerModule } from '@angular/service-worker';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
    }),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Step 4: Create a weather service

Create a new weather service that will fetch the current weather for a user’s location. Add the following code to a new file called weather.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class WeatherService {
  private baseUrl = 'https://api.openweathermap.org/data/2.5/weather';
  private apiKey = 'your-api-key';

  constructor(private http: HttpClient) {}

  getCurrentWeather(lat: number, lon: number) {
    const url = `${this.baseUrl}?lat=${lat}&lon=${lon}&appid=${this.apiKey}`;
    return this.http.get(url);
  }
}

Replace your-api-key with your own OpenWeatherMap API key.

Step 5: Create a weather component

Create a new weather component that will display the current weather for a user’s location. Add the following code to a new file called weather.component.ts:

import { Component, OnInit } from '@angular/core';
import { WeatherService } from '../weather.service';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.scss'],
})
export class WeatherComponent implements OnInit {
  weather: any;

  constructor(private weatherService: WeatherService) {}

  ngOnInit(): void {
    navigator.geolocation.getCurrentPosition((position) => {
      this.weatherService
        .getCurrentWeather(position.coords.latitude, position.coords.longitude)
        .subscribe((data) => {
          this.weather = data;
        });
    });
  }
}

This code uses the navigator.geolocation.getCurrentPosition method to get the user’s current location, and then calls the getCurrentWeather method of the WeatherService to fetch the current weather for that location.

Step 6: Create a weather template

Create a new weather template that will display the current weather for a user’s location. Add the following code to a new file called weather.component.html:

<div *ngIf="weather">
  <h1>{{ weather.name }} Weather</h1>
  <p>Temperature: {{ weather.main.temp }}&deg;C</p>
  <p>Humidity: {{ weather.main.humidity }}%</p>
  <p>Wind Speed: {{ weather.wind.speed }} km/h</p>
</div>

This code uses Angular’s *ngIf directive to only display the weather information if it is available.

Step 7: Add the weather component to the app component

Add the weather component to the app component by adding the following code to the app.component.html file:

<app-weather></app-weather>

Step 8: Build and deploy your application

Build your application using the ng build –prod command, and deploy it to a web server that supports HTTPS.

Step 9: Test your application

Test your application by opening it in a web browser and allowing it to access your location. Verify that it is displaying the current weather for your location. You can also test offline support by disabling your internet connection and refreshing the page.

Conclusion

Angular Service Workers and PWA are powerful tools that can help improve the performance and user experience of web applications. They are relatively easy to implement and can provide significant benefits to your application. If you are building a web application, consider using Angular Service Workers and PWA to provide a fast, reliable, and seamless user experience.

For more updates on such topics, please follow our LinkedIn page- Frontend Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: