Attention! This repository is archived and the library has been moved to tinkoff/ng-web-apis monorepository
Part of Web APIs for Angular
This is a library for comfortable use of Web Workers API with Angular.
If you do not have @ng-web-apis/common:
npm i @ng-web-apis/common
Now install the package:
npm i @ng-web-apis/workers
Create a worker and use it in a template with AsyncPipe
:
import {WebWorker} from '@ng-web-apis/workers';
function compute(data: number): number {
return data ** 2;
}
@Component({
template: `
Computed Result:
<ng-container *ngIf="worker | async as event">{{ event.data }}</ng-container>
<form (ngSubmit)="worker.postMessage(input.value)">
<input #input />
<button type="submit">Send to worker</button>
</form>
`,
})
class SomeComponent {
readonly worker = WebWorker.fromFunction<number, number>(compute);
}
To get data from the worker event, use the toData operator
import {toData, WebWorker} from '@ng-web-apis/workers';
function compute(data: number): number {
return data ** 2;
}
@Component({
template: `
Computed Result: {{ workerData$ | async }}
<form (ngSubmit)="worker.postMessage(input.value)">
<input #input />
<button type="submit">Send to worker</button>
</form>
`,
})
class SomeComponent {
readonly worker = WebWorker.fromFunction<number, number>(compute);
readonly workerData$ = this.worker.pipe(toData());
}
It's the same with WorkerPipe
only:
import {WorkerModule} from '@ng-web-apis/workers';
import {NgModule} from '@angular/core';
@NgModule({
imports: [WorkerModule],
declarations: [SomeComponent],
})
class SomeModule {}
import {WorkerExecutor, WebWorker} from '@ng-web-apis/workers';
import {FormControl} from '@angular/forms';
@Component({
template: `
Computed Result: {{ value | waWorker: changeData | async }}
<input [(ngModel)]="value" />
`,
})
class SomeComponent {
value: string;
changeData(data: string): string {
return `${data} (changed)`;
}
}
Other Web APIs for Angular by @ng-web-apis
Do you also want to open-source something, but hate the collateral work? Check out this Angular Open-source Library Starter we’ve created for our projects. It got you covered on continuous integration, pre-commit checks, linting, versioning + changelog, code coverage and all that jazz.