javascript / expert
Snippet
Signal-Wrapped Web Worker Orchestration
Offloading heavy computations to Web Workers prevents the main thread from blocking, ensuring smooth UI performance. By wrapping the worker's lifecycle in Angular Signals, you can declaratively track the processing state and integrate asynchronous results directly into the reactive template graph.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Injectable, signal, computed } from '@angular/core';@Injectable({ providedIn: 'root' })export class DataProcessorService {private status = signal<'idle' | 'busy'>('idle');isProcessing = computed(() => this.status() === 'busy');async processLargeDataset(data: any[]) {this.status.set('busy');const worker = new Worker(new URL('./processor.worker', import.meta.url));return new Promise((resolve) => {worker.onmessage = ({ data: result }) => {this.status.set('idle');resolve(result);};worker.postMessage(data);});}}
angular
Breakdown
1
isProcessing = computed(() => this.status() === 'busy');
Derives a reactive boolean signal from a private state signal to drive UI feedback.
2
const worker = new Worker(new URL('./processor.worker', import.meta.url));
Spawns a new OS-level thread for parallel execution of JavaScript logic.