Last active
March 27, 2018 10:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.addEventListener('message', function(event) { | |
const number1 = event.data.number1; | |
const number2 = event.data.number2; | |
self.postMessage({result: number1+number2}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.