Return JSON Function Data and Fill DIV

0

I want to learn how to retrieve data from a function that does a GET in an API and returns me the JSON. I want to retrieve the data and populate a list ... with ng-repeat .

It's happening to come undefined and then I do not even know what to put in ng-repeat .

Angular JS

/* Factory */
App.factory('dealerFactory', ['$http', function($http) {
   var factory = {
      obterDados: _obterDados
   }

   // Lista de Concessionárias
   function _obterDados() {
      $http.get("http://localhost:8888/dealers").then(
         function(response){
            return response.data;
         }
      );
   }

   return factory;
}]);

App.controller('ListaCtrl', ['$scope', 'dealerFactory', function($scope, dealerFactory){

   $scope.dealers = [];
   $scope.dealers = dealerFactory.obterDados();

}]);

HTML

<ion-content ng-controller="ListaCtrl">
   <ion-list>
      <ion-item ng-repeat="{{ result in dealers }}" id="{{result.id}}">
         <h3>{{result.dealer}}</h3>
         <h4>{{result.stars}}</h4>
      </ion-item>
   </ion-list>
</ion-content>

Update:

When I make the code below for debug reasons only, I get undefined. The URL is right, it's bringing the jSON. I tested LINK in the browser and also gave console.log on the function return and brought me the data.

$scope.dealers = [];
$scope.dealers = dealerFactory.obterDados();
console.log($scope.dealers);

I think it's something related to Asynchronization. The variable has not changed yet, and return runs first ... I do not know how to solve it.

    
asked by anonymous 30.03.2016 / 21:03

1 answer

0

Well, first create the variable in the angular scope,

App.controller('ListaCtrl', ['$scope', 'dealerFactory', 
 function($scope,    dealerFactory){

$scope.dealers = [];
$scope.dealers = dealerFactory.obterDados();

// não precisa fazer mais nada
}]);

HTML

<ion-content ng-controller="ListaCtrl">
//correção nova aqui
 <ion-list ng-repeat="dealer in dealers">
   <ion-item id="{{dealer.id}}">
      <h3>{{dealer.dealer}}</h3>
      <h4>{{dealer.stars}}</h4>
   </ion-item>
 </ion-list>
</ion-content>

CORRECTION:

 App.factory('dealerFactory', ['$http', function($http) {
   var factory = {
    obterDados: _obterDados
   }

function _obterDados() {
   $http.get("http://localhost:8888/dealers/1").then(
     function(data){
//como voce usou o then e não o sucess o data que tem o json esta dentro de
//data.data e não somente data
//se voce usa o .sucess ao invés do .then, usa apenas data no retorno
        return data.data;
      }
   );
 }

   return factory;
}]);

I think this solves your problem, now you need to see if your API is actually returning the data, because you said that sometimes it returns undefined, maybe the API has a problem.

Anything please let me know,

I hope I have helped

Hugs!

    
30.03.2016 / 21:16