NashTech Insights

Advanced Guide to Service Worker Communication, Notifications, and Configuration in Angular (Part-2)

Alka Vats
Alka Vats
Table of Contents

In the previous series on this topic, we learned about the angular service worker and PWA and its implementations. If you haven’t checked, first check out Part-1 here.

Introduction:

Service Workers are powerful tools that can help improve the performance and user experience of web applications. They work in the background and can cache assets, provide push notifications, and handle background synchronization. In this advanced guide, we will explore Service Worker communication, notifications, and configuration in Angular.
You can refer here if you want to learn more about it.

Service Worker Communication

Service Workers can communicate with the main thread of the application using the postMessage() method. This method allows the Service Worker to send messages to the main thread, and vice versa. Here’s an example of how to use postMessage() to communicate between the Service Worker and the main thread:

// Service Worker
self.addEventListener('message', (event) => {
  if (event.data.type === 'ping') {
    console.log('Service Worker received ping message');
    self.postMessage({ type: 'pong' });
  }
});

// Main thread
navigator.serviceWorker.controller.postMessage({ type: 'ping' });
navigator.serviceWorker.addEventListener('message', (event) => {
  if (event.data.type === 'pong') {
    console.log('Main thread received pong message');
  }
});

In this example, the Service Worker listens for a ‘ping’ message, and when it receives it, it sends a ‘pong’ message back to the main thread. The main thread sends the ‘ping’ message to the Service Worker using the postMessage() method, and listens for the ‘pong’ message using the ServiceWorkerContainer.addEventListener() method.

Service Worker Notifications

Service Workers can handle push notifications, allowing you to send notifications to your users even when they are not actively using your application. Here’s an example of how to use push notifications with a Service Worker in Angular:

Step 1: Create a Service Worker

Create a Service Worker file in your Angular project. Add the following code to the file:

// service-worker.js
self.addEventListener('push', (event) => {
  const title = 'Push Notification';
  const options = {
    body: event.data.text(),
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

This code listens for a ‘push’ event, and when it receives it, it creates a new notification with the title ‘Push Notification’ and the body set to the text of the push message.

Step 2: Register the Service Worker

Register the Service Worker in your Angular application. Add the following code to your app.module.ts file:

// app.module.ts
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('service-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 service-worker.js file as the Service Worker for your application.

Step 3: Send a Push Notification

Send a push notification to your application. You can use a service like Firebase Cloud Messaging to send a push notification, or use a tool like curl to send a notification from the command line. Here’s an example of how to send a push notification using curl:

curl -X POST \
  --header "Authorization: key=YOUR_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{"notification": {"title": "Push Notification", "body": "Hello World!"}, "to": "YOUR_DEVICE_TOKEN"}' \
  https://fcm.googleapis.com/fcm/send

This code sends a push notification with the title ‘Push Notification’ and the body ‘Hello World!’ to the device with the specified device token.

Step 4: Handle the Push Notification

Handle the push notification in your Angular application. Add the following code to your app.component.ts file:

// app.component.ts
import { Component } from '@angular/core';
import { SwPush } from '@angular/service-worker';

@Component({
  selector: 'app-root',
  template: `
    <h1>Push Notifications</h1>
    <button (click)="subscribe()">Subscribe</button>
    <button (click)="unsubscribe()">Unsubscribe</button>
  `,
})
export class AppComponent {
  constructor(private swPush: SwPush) {}

  subscribe() {
    this.swPush.requestSubscription({ serverPublicKey: 'YOUR_PUBLIC_KEY' }).then(
      (subscription) => console.log(subscription),
      (error) => console.error(error)
    );
  }

  unsubscribe() {
    this.swPush.unsubscribe().then(
      () => console.log('Unsubscribed'),
      (error) => console.error(error)
    );
  }
}

This code uses the SwPush service from the @angular/service-worker package to subscribe to push notifications and provides buttons to subscribe and unsubscribe from push notifications. When the user clicks the ‘Subscribe’ button, the application requests a subscription from the push service and logs the subscription to the console. When the user clicks the ‘Unsubscribe’ button, the application unsubscribes from push notifications and logs a message to the console.

Service Worker in Production

When deploying your Angular application to production, it’s important to configure your Service Worker properly to ensure that it works correctly. Here are some best practices for configuring your Service Worker in production:

  • Use HTTPS: Service Workers require HTTPS to work properly. Make sure that your web server is configured to use HTTPS.
  • Use a separate domain: Use a separate domain for your Service Worker to avoid conflicts with other resources on your site.
  • Cache assets: Cache your application’s assets using the Service Worker to improve performance and reduce the load on your server.
  • Update your Service Worker: Update your Service Worker regularly to ensure that your application is using the latest version.
  • Test your Service Worker: Test your Service Worker thoroughly to ensure that it works correctly in production.

Service Worker Configuration in Angular

Configuring your Service Worker in Angular 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.

Conclusion

Service Workers are powerful tools that can help improve the performance and user experience of web applications. In this advanced guide, we explored Service Worker communication, notifications, and configuration in Angular. By following these best practices, you can ensure that your Service Worker is configured properly and works correctly in production.

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: