2

So I'm writing a simple app to just return census data for each state. I have an $http request that gets two JSON files and combines them. I have this working fine in the controller, but this seems better suited for something that I write in a service and then inject that data from the service into the controller. But I can't figure out how to do that.

Here's what I have so far:

app.js

app.factory('stateData', ['$http','$q', function($http, $q) {

  var combine;
  var states = $http.get('js/data/states.json');
  var rates = $http.get('http://api.census.gov/data/2013/acs1/profile?get=DP03_0128PE&for=state:*&key=b143975cec2fd367b0e0d73ba6417a6a47d097c7');

  combine = $q.all([states,rates]).then(function(result) {
    var combine = [];
    var states, rates;

    angular.forEach(result, function(response) {
      combine.push(response.data);
    });

    states = combine[0],
    rates = combine[1];

    for(var s = 0; s < states.length; s++) {
      for(var r = 0; r < rates.length; r++) {
        if(states[s].code === rates[r][1]) {
          states[s].rate = rates[r][0];
        }
      }
    }

    return states;
  });

  return combine;
}]);

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

  $scope.states = stateData;
}]);

If I run console.log($scope.states) I get back:

Object {then: function, catch: function, finally: function} 

So obviously there's an issue calling the data from $http before it's been returned.

Thanks for any help you all can offer.

ughitsaaron
  • 517
  • 4
  • 10
  • 1
    It is a promise object, you need to chain through `stateData.then(function(states){ $scope.states = states });` – PSL Oct 08 '14 at 01:25
  • There are numerous hundreds of posts that relates to this... Just marked with one of them as duplicate.. You can check this answer which covers what is an ajax call and what is meant be asynchronous and how do you handle data returned from ajax call.. http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – PSL Oct 08 '14 at 01:32
  • 1
    Just to add on `$scope.states = stateData;` used to auto unwrap promises prior to 1.2 version of angular. It is available only as an optional configuration anymore (Not sure about 1.3). – PSL Oct 08 '14 at 01:40
  • Thanks for linking to the duplicate question. Sorry for the mistake. That question didn't come up when I was searching around. Just an etiquette question: what's the proper thing for me to do now that this question has been marked a duplicate? – ughitsaaron Oct 08 '14 at 02:13

1 Answers1

2

The service returns a promise, so you need to call .then and use to callback to set the $scope value:

$scope.states = [];
stateData.then(function(data) {
    $scope.states = data;
});  
Brennan
  • 5,632
  • 2
  • 17
  • 24