Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using web-workers in Angular to off-load data intensive calculations. Considering a trivial addition here.
import { Component, OnInit } from "@angular/core";
selector: "app-dashboard",
templateUrl: "dashboard.component.html"
export class DashboardComponent implements OnInit {
constructor() {}
ngOnInit() {
const worker = new Worker("assets/js/service.sw.js");
worker.addEventListener("message", (event) => {
console.log(`Thats the result of addition: ${}`);
worker.postMessage({number1: 1, number2: 2});
self.addEventListener('message', function(event) {
const number1 =;
const number2 =;
self.postMessage({result: number1+number2});
Copy link

jyotendra commented Mar 27, 2018

The file "service.worker.js" goes in angular's "asset/js" folder.

More on workers can be found on MDN. Note that, web-workers and service-workers are different and we are currently talking about web-workers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment