We want to get started with Web Workers in Angular
Approach
New Project
ng new WW --routing --style=scss --defaults --skipTests=true
cd WW
New Worker
Generate app.worker.ts
in the app
folder:
ng generate web-worker app
The Angular CLI logs the following:
CREATE tsconfig.worker.json (289 bytes)
CREATE src/app/app.worker.ts (157 bytes)
UPDATE angular.json (4273 bytes)
UPDATE src/app/app.component.ts (591 bytes)
If we look in app.components.ts
we see the following web worker scaffolding added.
We will move this to src/app/services/worker.service.ts
to show that this scaffolding can be run from any service.
Web Worker Service
Generate src/app/services/worker.service.ts
:
ng g service services/worker
Move the scaffolding to the service constructor:
constructor() {
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.
// You should add a fallback so that your program still executes correctly.
}
}
Note that we changed the instantion of the worker from:
const worker = new Worker('./app.worker', { type: 'module' })
To:
const worker = new Worker('../app.worker', { type: 'module' })
Also NOTE THAT IN ANGUALR 12 the worker constructor
has changed to:
const worker = new Worker(new URL('../app.worker', import.meta.url))
And inject the service in app.component.ts.
:
constructor(private ws: WorkerService) { }
Start the app:
ng serve -o
We should see that it logs page got message hello
in the web developer console.