How to Redeem External Data JSON

1

I'm learning AngularJs with Apigility. I'm having some questions and I think I can only understand by asking ...

I have this code here:

App.controller('ListaCtrl', ['$scope', function($scope){
  $scope.id     = 1;
  $scope.dealer = "Teste";
  $scope.stars  = "5 Estrelas";
}]);

How do I retrieve an external JSON into an API?

I'm seeing this code here:

var noticias = $http.get("http://localhost:8888/dealers")
    .then(function(response) {
        console.log(response);
     });

But I can not make it work. I'm putting it inside App.controller('ListaCtrl') . I do not know if it's right.

    
asked by anonymous 30.03.2016 / 18:42

1 answer

2

To use within controller , you need to pass the $http service being used, as follows:

App.controller('ListaCtrl', ['$scope', '$http', function($scope, $http){
  $scope.id     = 1;
  $scope.dealer = "Teste";
  $scope.stars  = "5 Estrelas";

  /* Seu $http */
  var noticias = $http.get("http://localhost:8888/dealers")
      .then(function(response) {
          console.log(response);
      });
}]);

It is the same logic of using $scope , in order to use the service, you need to reference it in controller to be used.

Complementing the answer, you'd ideally use this $http in a service, be it a service or factory . Of course this fits your initial question, but it's the best practice. Have that little hammer in mind:

  • Controller - > The controller needs to use the data, but it does not interest the controller as will be obtained, it is only important to receive the data.
  • Service - > You should provide the data for controller , which will be done after that does not matter, it only matters that he provided the data.

Example of using factory to receive the data in the controller:

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

    function _obterDados() {
        $http.get("http://localhost:8888/dealers").then(
            function(response) {return response;}
        );
    }

    return factory;
}]);

/* Seu Controller */
App.controller('ListaCtrl', ['$scope', 'minhaFactory', function($scope, minhaFactory){
    $scope.id     = 1;
    $scope.dealer = "Teste";
    $scope.stars  = "5 Estrelas";

    /* Seu $http */
    var noticias = minhaFactory.obterDados();
}]);
    
30.03.2016 / 19:05