Angular question detail
How do you add web workers in your application?
You can add web worker anywhere in your application. For example, If the file that contains your expensive computation is src/app/app.component.ts, you can add a Web Worker using ng generate web-worker app command which will create src/app/app.worker.ts web worker file. This command will perform below actions,
- Configure your project to use Web Workers
- Adds app.worker.ts to receive messages
addEventListener('message', ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});
- The component
app.component.tsfile updated with web worker file
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./app.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
console.log('page got message: $\{data\}');
};
worker.postMessage('hello');
} else {
// Web Workers are not supported in this environment.
}
Note: You may need to refactor your initial scaffolding web worker code for sending messages to and from.