I have angular app created with Angular CLI
. I want to use Web Worker
for creating thread
.
My idea is to do heavy calculation in background thread
and post back response to the main thread
once completed.
I have worker.js
self.addEventListener('message', (evt) => {
switch (evt.data.cmd) {
case 'CALCULATE':{
let payload = evt.data.payload;
let response = calculateFunction(payload);
let response = {
cmd: 'RESPONSE',
payload: response
}
postMessage(response);
break;
}
default:
throw Error(`Invalid command: ${evt.data.cmd}`);
}
});
In Component :
private worker: Worker;
constructor() {
this.initWebWorker();
}
initWebWorker(){
let url = '/dist/assets/workers/worker.js';
this.worker = new Worker(url);
this.worker.addEventListener('message', (evt)=>{
switch (evt.data.cmd) {
case 'RESPONSE':{
let payload = evt.data.payload;
console.log(payload)
break;
}
default:
throw Error(`Invalid command: ${evt.data.cmd}`);
}
});
}
Posting message to Worker
from component
this.worker.postMessage({cmd: 'CALCULATE', payload: payload});
This is working as expected. But I have couple of questions as
- I have placed
worker.js
inassets
folder so that it should get copied onng build
worker.js
isJS
file notTS
. I hope I can useTS
instead- To use
TS
I can addentry
inwebpack.config
and it will generatebundle
for me. But I don't want toeject webpack configuration
fromAngular CLI
project - I have checked this package but with this I can only run the function is thread, I want code separation of all the function related for computation in
worker file
So how can I use Web worker
in Angular CLI project
better way. I tried to search for the same but not found good article on this.
Reference: Angular CLI generated app with Web Workers