Problem whit $http.get and json

Hi, i have this code:

-SERVICES.JS

serv.factory('loadData', function($http) {

  var test = [];
  var uri = 'http://jsonplaceholder.typicode.com/posts';

  $http.get(uri).then(function(response) {
      test = response.data;
    });

	return {
		all : function() {
        return test;
    }
	};

});

-CONTROLLER.JS

ctrl.controller('HomeCtrl', function($scope, $ionicPopup, loadData) {

 $scope.prova = loadData.all();

});

-HOME.HTML

<ion-view view-title="Home">
  <ion-content>
    <h1>Home</h1>
{{prova}}
  </ion-content>
</ion-view>

In html code, my variable prova is null, i see in html only this []

where i wrong?

ps: in service if i add value a test, this work.
i think problem is $http.get because not add value json a this variable

try loadData.test instead of loadData.all();

no work, problem is in $http.get

upp upp…!
nothing…?

The problem is …

loadData.all();

is just a function wich retrieves the contents of

var test

But you have to think async … your test var is still empty because $http is probably not ready yet executing.

The solution is to make a promise function in the factory. In the function execute the $http and then return the reject/resolve object back to the controller. If the controller recieves a resolve, fill the scope var with the result of the resolve object.

You need to call the $http method from within the factory returning function, like this:

serv.factory('loadData', function($http) {

  var uri = 'http://jsonplaceholder.typicode.com/posts';

	return {
		all : function() {
                   return $http.get(uri).then(function(response) {
                           return response.data;
                   });
            }
	};

});
1 Like

yes, this work.
but if i want use variable?

what would the variable do?