Skip to content

Instantly share code, notes, and snippets.

@jyotendra
Last active March 27, 2018 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyotendra/b7565ab18912a006bb92a3f4ffeefc10 to your computer and use it in GitHub Desktop.
Save jyotendra/b7565ab18912a006bb92a3f4ffeefc10 to your computer and use it in GitHub Desktop.
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

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