Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Web Worker in AngularJS?

I'm using AngularJS Seed and I want to see a working implementation of a Web Worker.

I want to make a simple Web Worker work in order to understand it, but I'm running into an issue with the functionality.

I have the Web Worker code in the services.js like so:

'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 file doWork.js and its contents are:

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

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

'use strict';

/* Controllers */
var app = angular.module("myApp.controllers",[]);

app.controller('MyCtrl1', [ '$scope', function($scope) {


}]).controller('MyCtrl2', [ '$scope', function($scope) {


}]);

What I want is to see the output of the Web Worker.

The error I get with this setup is:

Uncaught TypeError: Cannot call method 'factory' of undefined

like image 435
achudars Avatar asked Aug 08 '13 17:08

achudars


2 Answers

You have a syntax error?

change

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

to

/* Services */
var app = angular.module('myApp.services', []);
like image 129
coreyb Avatar answered Sep 22 '22 15:09

coreyb


You need to have something to resolve the promise returned from your service. Something along the lines of

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

Also, you'll need to inject the service into the controller that calls the service.

Take a look at this post for another way of dealing with web workers in AngularJS.

And you might also want to get acquainted with the promise implementation, $q in AngularJS

like image 39
Steen Avatar answered Sep 19 '22 15:09

Steen