How to use a web worker in AngularJS?

I am using AngularJS Seed and want to see a working implementation of a web worker.

I want a simple web worker to work to figure this out, but I have a problem with functionality.

I have a web worker code in services.js , for example:

'use strict'; /* Services */ var app = angular.module('myApp.services', []). app.factory("HelloWorldService",['$q',function($q){ var worker = new Worker('js/doWork.js'); var defer; worker.addEventListener('message', function(e) { console.log('Worker said: ', e.data); defer.resolve(e.data); }, false); return { doWork : function(myData){ defer = $q.defer(); worker.postMessage(myData); // Send data to our worker. return defer.promise; } }; }]); 

In the js folder, I have a doWork.js file, and its contents:

 self.addEventListener('message', function(e) { self.postMessage(e.data); }, false); 

My controllers.js file is empty and it looks like this:

 'use strict'; /* Controllers */ var app = angular.module("myApp.controllers",[]); app.controller('MyCtrl1', [ '$scope', function($scope) { }]).controller('MyCtrl2', [ '$scope', function($scope) { }]); 

I want to see the results of a web worker.

Error with this setting:

Uncaught TypeError: unable to call factory 'undefined method

+6
source share
2 answers

Do you have a syntax error?

change

 /* Services */ var app = angular.module('myApp.services', []). 

to

 /* Services */ var app = angular.module('myApp.services', []); 
+2
source

You need to decide something for the promise received from your service. Something along the lines

 var promise = HelloWorldService.doWork( input ); promise.then( function( allWentGoodMessage ){ // green path code goes here }, function( somethingWentBadMessage ){ // error handling code goes here } ); 

In addition, you will need to enter the service into the controller that calls the service.

Take a look at this post for another way to work with web workers in AngularJS.

And you can also get to know the implementation of the promise, $q in AngularJS

+1
source

Source: https://habr.com/ru/post/951340/


All Articles