A new version
Based on the decision, which you can find here , I created a simple class that uses WebWorker to perform their tasks.
You have 3 files for working worker.
file-loader.d.ts - need to download WebWorker files
declare module "file-loader?name=[name].js!*" { const value: string; export = value; }
background-worker.ts - the class available in your application
import * as workerPath from "file-loader?name=[name].js!./web-worker-example"; class BackgroundWorker { constructor() { let worker = new Worker(workerPath); worker.onmessage = this.handleMessage; worker.postMessage('Caller: Help Me for background Work'); // Message content can contain only Javascript Objects // // For Documentation: // https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage // } private handleMessage( this: Worker, message: MessageEvent ) { console.log( message.data ); switch( message.data ) { case 'Worker: Working': // ... Something To Do ... break; case 'Worker: Ok, I will Do It': // ... Something To Do ... break; case 'Worker: No, I can not': // ... Something To Do ... break; case 'Worker: Done': this.terminate(); break; } } }
web worker-example.ts
// ****************************************************************** Worker Bridge // self is a keyword: Reference to this Worker self.onmessage = bridge; function bridge( message: MessageEvent ) { HandleWork( message.data ); CallBack('Done'); // use: // self.close(); // if you need to terminate worker from Worker Environment. } function CallBack( message: string ) { self.postMessage('Worker: ' + message, undefined); } // ****************************************************************** Worker Body function HandleWork( workTask: string ) { if( workTask == 'Caller: Help Me for background Work' ) { CallBack('Ok, I will Do It'); DoVeryComplexWork(); return; } CallBack('No, I can not'); } function DoVeryComplexWork() { // ... Something To Do ... // Example: for( let i: number = 0; i < 1000000000; i++ ) { if( i % 100000000 == 0 ) { CallBack('Working'); } } }
To start Worker, simply create an instance of employee new BackgroundWorker() and take a look at the console.
Old version
I had the same problem and solved it by creating a service extending the WebWorker class. In practice, the service works by passing WebWorker two things, data and a function that develop the data.
I posted an example on GitHub. All the necessary logic is in the following two files.
fibonacci-worker.service.ts
worker.ts
See app.component.ts for call methods.
Sincerely.
source share