Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngualrJS $http returns undefined?

According to AngularJS, my $http call through a service from my controller is returning undefined?

What seems to be the issue here? I am trying to return the data called, but once passed to the controller the data becomes undefined?

JavaScript

var myStore = angular.module('myStore', [])

    .controller('StoreController', ['$scope', 'dataService', function ($scope,  dataService) {
      $scope.products = dataService.getData();
    }])

    .service('dataService', ['$http', function($http) {
      this.getData = function() {
        $http.get('assets/scripts/data/products.json')
              .then(function(data) {
                return data;
              });
      };
    }]);

HTML

<div class="content">
  <ul>
    <li ng-repeat="product in products.products">{{product.productName}}</li>
  </ul>
</div>

I understand that $http, $q, and $resource all return promises, but I thought I had covered that with .then.

like image 511
Aaron Brewer Avatar asked Feb 11 '23 09:02

Aaron Brewer


1 Answers

The problem could be that you are not returning the promise created by $http.get in your dataService.getData function. In other words, you may solve your undefined issue by changing what you have to this:

.service('dataService', ['$http', function($http) {
    this.getData = function() { 
        return $http.get...
    };
}

If you had multiple calls to $http.get within dataService.getData, here is how you might handle them.

.service('dataService', ['$http', function($http) {
    this.getData = function() {
        var combinedData, promise;
        combinedData = {};
        promise = $http.get(<resource1>);
        promise.then(function (data1) {
            combinedData['resource1Response'] = data1;
            return $http.get(<resource2>);
        });
        return promise.then(function (data2) {
            combinedData['resource2Response'] = data2;
            return combinedData;
        });
    };
}]);

A much cleaner way, however, would be to use $q.all

.service('dataService', ['$http', '$q', function($http, $q) {
    this.getData = function() {
        var combinedData, promises;
        combinedData = {};
        promises = $q.all([
            $http.get(<resource1>),
            $http.get(<resource2>)
        ]);
        return promises.then(function (allData) {
            console.log('resource1 response', allData[0]);
            console.log('resource2 response', allData[1]);
            return allData;
        });
    };
}]);
like image 113
maxenglander Avatar answered Feb 12 '23 22:02

maxenglander