How to use a Web Worker in AngularJS?

2019-06-20 07:26发布

问题:

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

回答1:

You have a syntax error?

change

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

to

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


回答2:

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