Problem whit $http.get and json


#1

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


#2

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


#3

no work, problem is in $http.get


#4

upp upp…!
nothing…?


#5

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.


#6

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

});

#7

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


#8

what would the variable do?