Mike Fisher
Mike Fisher

Reputation: 921

Unable to consume an Angular service from a Controller

So I've done extensive research and read many tutorials but I can't find a straightforward answer to what I'm trying to accomplish.

I'm simply trying to access a JSON object stored at JSON-Generator.com and stick it in a table and repeat it. Sounds simple enough but it seems there many different ways to do this and all the sources leave out the one piece of info I need.

if I console.log eventsService inside the controller it returns a constructor, if I console.log eventsService.data it returns undefined.

How do I access the data returned from $http in my controller?

// CONTROLLERS


app.controller('currentTradeshowsController', ['$scope', 'eventsService', function($scope, eventsService){


  $scope.events = eventsService.data;


}]);


    // SERVICES


app.service('eventsService',function($http){

  var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';


  $http({method: 'GET', url: eventsUrl}).
    success(function(data){
      // not sure what to write here....
      return data;

    })

    .error(function(){
      console.log('ah shit');
    })



});

Upvotes: 0

Views: 49

Answers (1)

doodeec
doodeec

Reputation: 2927

first of all, $http call is asynchronous, so you probably want to use promises to load the data correctly into scope variable

second - you need to return something from the service to make it work outside of the service declaration function

controller

app.controller('currentTradeshowsController', function($scope, eventsService){
    eventsService.getData().then(function(data) {
        $scope.events = data;
    });
});

service

app.service('eventsService',function($http){
    var eventsUrl = 'http://www.json-generator.com/j/bVWJaYaWoO?indent=4';

    return {
        getData: function() {
            return $http.get(eventsUrl);
        }
    }
});

$http.get is a shorthand for GET request, and it returns a promise, so you can simply use it with .then in the controller

Upvotes: 1

Related Questions