Aaron Rabinowitz
Aaron Rabinowitz

Reputation: 357

Factory method HTTP not working

I cannot get this json call from my factory jsonLanguage.

My code:

var App = angular.module('App', []);
var theLanguage = 'english';
App.factory('jsonLanguage', function($http){
    var theLanguage = 'english';
    return {

        get: function(theLanguage){
            var url = theLanguage + '.json';
            $http.get(url);
        }
    }

});
App.controller('mainController', function($scope, $http, $log, jsonLanguage) {

  //$http.get(theLanguage + '.json')

       jsonLanguage.success(function(res){  //here is the problem I tried .then and tried res.data no luck :(
          $scope.language = res;
$log.debug($scope.language);


        });
$log.debug($scope.language);
angular.forEach($scope.letter, function(single) {
        $log.log("hello worldsss");
 $log.log(single);
    });
});

App.controller('intervalController', function($scope, $log) {
    this.$log = $log;
    //var name = $scope.single;
    angular.forEach($scope.letter, function(single) {
        $log.log("hello worldsss");
 $log.log(single);
    });
    //$log.log(name);
  $log.log('Hello World!');

});

App.controller('clickController', function($scope) {

});

I tried jsonLanguage, and then and tried res.data with no luck.

Upvotes: 1

Views: 86

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

Here you missed couple of things:

  1. Return $http promise from service get method

    get: function(theLanguage){
        return $http.get(url);
    }
    
  2. Call factory get method & get data inside its promise success by putting .then over that method call.

    jsonLanguage.get($scope.language).then(function(res){ 
       $scope.language = res.data;
    });
    

Upvotes: 3

Iceman
Iceman

Reputation: 6145

Return the $http promise, so that you can resolve it later using then.

return {
  get: function(theLanguage) {
    var url = theLanguage + '.json';
    return $http.get(url);
  }
}

Now you can use it like jsonLanguage.get().then()

Upvotes: 1

frosty
frosty

Reputation: 21762

You need to call jsonLanguage.get().then(/**insert callback fn here*/) in order to call the service.

And in order for that to work, you need to return the promise in your get function.

get: function(theLanguage){
    return $http.get(url);
}

Upvotes: 2

Related Questions