These are the steps to create a service that interacts with Web Workers:
1. Create the Web Worker Service (worker.service.ts)
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class WorkerService {
private worker: Worker;
private messageSubject = new Subject<any>();
constructor() {
this.worker = new Worker(new URL('./app.worker', import.meta.url));
this.worker.onmessage = ({ data }) => this.messageSubject.next(data);
}
runInBackground<T>(data: any): Observable<T> {
this.worker.postMessage(data);
return this.messageSubject.asObservable() as Observable<T>;
}
terminate() {
this.worker.terminate();
}
}
2. Create the Worker File (app.worker.ts)
/// <reference lib="webworker" />
addEventListener('message', ({ data }) => {
// Perform CPU-intensive tasks here
const result = heavyCalculation(data);
postMessage(result);
});
function heavyCalculation(input: any): any {
// Your background processing logic
return input; // Replace with actual processing
}
3. Register the Worker in tsconfig.json
{
"compilerOptions": {
"lib": ["webworker"]
}
}
4. Usage Example
@Component({...})
export class MyComponent {
constructor(private workerService: WorkerService) {}
processData() {
const largeData = {...}; // Your data
this.workerService.runInBackground(largeData)
.subscribe(result => {
console.log('Worker result:', result);
});
}
}