Search code examples
javascriptangularjsweb-worker

how to use web worker in angular js for calling service?


I make a simple program to call http service.First I call http service in my controller and display data on view given plunker

http://plnkr.co/edit/sHLQJaH7ElHVU6xweQuS?p=preview

but I need to call service using web workers and send data to my controller .can we call service in background ? I got one solution this but not working for me

AngularJS and web workers

I used this solution in my plunker http://plnkr.co/edit/7OZvbFnHxuVLUtDFf1hm?p=catalogue

not able to implement web worker in my project could you please tell me how to use webworkser in angular js

.factory("HelloWorldService",['$q',function($q){

    var worker = new Worker('https://dl.dropboxusercontent.com/s/9wkl32e23vdvs6h/default.json?dl=0');
    var defer = $q.defer();
    worker.addEventListener('message', function(e) {
      console.log('Worker said: ', e.data);
      defer.resolve(e.data);
    }, false);

    return {
        doWork : function(successcallback,errorcallback){
            defer = $q.defer();
           // worker.postMessage(myData); // Send data to our worker. 
            return defer.promise;
        }
    };

}]);

Solution

  • I fixed your code and build small sample for you.

    1. pnkr is a bit slow for your sample data, so you'll have to be patient to see the result (wait som 30sec for sure)
    2. http://plnkr.co/edit/JXoylu9RbkY4hepTgirJ?p=preview

    Due to the fact that the worker is plain JS, and for sample reasons I wanted to keep everything in one file and wanted the source to be compatible in IE as well, I used URL.createObjectURL, but you can just put the download scipt in seperate file.

    In this case using worker is useless, because you are not doing any work there, just downloading stuff, better use $http.get

    The important part for worker:

     doWork : function(){
           var worker = new Worker(blobURL);
            var defer = $q.defer();
    
            worker.addEventListener('message', function(e) {
            console.log('Worker said: ', e.data);
               defer.resolve(e.data);
              }, false);
    
            worker.postMessage("random data to worker"); // Send data to our worker. 
            return defer.promise;
        }
    

    And worker it self:

    var blobURL = URL.createObjectURL(new Blob([
        "onmessage = function (event) { \
            var xhr = new XMLHttpRequest(); \
            xhr.onreadystatechange=function(){\
            if (xhr.readyState==4 && xhr.status==200){\
                postMessage(xhr.responseText);\
            }\
        }; \
        xhr.open('GET', 'https://dl.dropboxusercontent.com/s/9wkl32e23vdvs6h/default.json?dl=0' , false); \
        xhr.send(); \
        }"
        ], { type: 'application/javascript' }));
    

    Calling from your controller

       HelloWorldService.doWork().then(function(data){
         console.log("data received to Ctrl");
       $scope.results = data;})
    

    For displaying results, I am just pushing out raw response in html, because question was about web workers.