What is this?
Web worker service for Angular 2.
Install
npm i angular2-web-worker
API
run
workerFunction
:- Must be a self-contained function. Cannot reference outside variables.
- You can import other libraries with
importScripts
though - These are okay:
-
;;const someFunction = input * input);;private webWorkerService = ;{thiswebWorkerService;}{return input * input;}
- These will probably NOT work:
-
// this is not okay because inside the context of the web worker `this` is not the same `this` as here.;// this is not okay because `_` doesn't exist in the web worker context (assuming tht `_` is available here to begin with);
data
: serializable data
runUrl
: Basically the same asurl
: The url you would use to create aWorker
instancedata
: Same as therun
method
terminate
: Calling this willterminate
the web worker, if it is still running.promise
: ThePromise
instance returned byrun
orrunUrl
.
Example
Check out angular2-web-worker-example for a sample project,
or see app/app.component.ts
for usage with an Angular 2 application.
export class AppComponent implements OnInit {
constructor(private _webWorkerService: WebWorkerService) {
}
ngOnInit() {
const input = 100;
const promise = this._webWorkerService.run(this.someCPUHeavyFunction, input);
promise.then(result => console.log(result));
}
someCPUHeavyFunction (input) {
return input * 10;
}
}