Aaron Rabinowitz Aaron Rabinowitz - 3 months ago 20
AngularJS Question

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.

Answer

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;
    });
    
Comments