bsr
bsr

Reputation: 58662

AngularJS - Processing asynchronous data in service

I want to get some asynchronous data in service, which needs to further processed there. The code is here at plnkr,

I simulate an async call with timeout, and once the data is received, the UI is updated. But, I also need to process the data in service (doubleData) and later use in my UI. Say, I need to augment the data with some specifics.

Since, data is null when {{doubleData()}} is called, it never populates it. How can I achieve a way to process data further in my service(which is populated async - say $http)?

index.html

<!doctype html>
<html ng-app="myApp"> 
    <head>
        <script type="text/javascript" src="../../../angular-1.0.2/angular.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div ng-controller="MainCtrl">
            {{data}}<br>
            {{doubleData()}}
        </div>
    </body>
</html>

script.js

var app = angular.module('myApp',[]);

app.factory('myService', function($timeout) {
  var data = [],
      doubleData = [];

  var myService = {};
  myService.async = function() {
    $timeout(function(){
        data.length = 0;
        for(var i = 0; i < 10; i++){
            data.push({val: Math.random()});                        
        }
    }, 5000); 
  };
  myService.data = function() { return data; };
  myService.doubleData = function() { 
    doubleData = []
    for (var i = 0; i < data.length; i++) {
        doubleData.push({val: 10* data[i]});   
    };    
    return doubleData;                 
  };

  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  myService.async();
  $scope.data = myService.data();
  $scope.doubleData = myService.doubleData;

});

Output (after 5 sec):

[{"val":0.4908415926620364},{"val":0.25592787051573396},{"val":0.8326190037187189},{"val":0.6478461190126836},{"val":0.8502937415614724},{"val":0.19280604855157435},{"val":0.06115643493831158},{"val":0.5100495833903551},{"val":0.4134843284264207},{"val":0.5548313041217625}]
[{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null}]

Upvotes: 0

Views: 7128

Answers (1)

Gloopy
Gloopy

Reputation: 37785

It looks like your issue is a typo in your for loop you need to access data[i].val:

for (var i = 0; i < data.length; i++) {
    doubleData.push({val: 10* data[i].val});   
};

Another way to do this (without watching for changes to variables) would be to bind doubleData the same way you are binding to data and call a function in your async callback to empty and populate doubleData with the calculated value. See this plnkr for an example.

Upvotes: 2

Related Questions