Skip to content

Instantly share code, notes, and snippets.

Embed
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";
@Component({
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: ${event.data.result}`);
});
worker.postMessage({number1: 1, number2: 2});
}
}
self.addEventListener('message', function(event) {
const number1 = event.data.number1;
const number2 = event.data.number2;
self.postMessage({result: number1+number2});
})
@jyotendra
Copy link
Author

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.

Loading

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