Problem in consuming JSON with AngularJS

-1

I'm trying to run a test to get the data from a JSON file but I'm not getting it.

  

app.component.html

</div><div ng-app="appCursos" ng-controller="meusCursos">
  <ul>
     <p> {{ cursos.id }}</p> 
  </ul>
</div>
  

json

{"id":7006,"content":"Hello, World!"}
  

app.curso.js

angular.module("appCursos").controller("meusCursos", function ($scope, $http) {
  var cursos = [];

  var baseUrl = 'http://rest-service.guides.spring.io/greeting';

  $http.get(baseUrl).then(function (response) {
    $scope.cursos = response.data;

  })
});

    
asked by anonymous 07.04.2018 / 08:27

1 answer

1

I could not replicate the error message that you got with your code, but an injecting error . When I fixed the problem, I was able to read JSON:

<!doctype html>
<html>  
    <head>
        <meta charset="utf-8">
    </head>
    <body ng-app="appCursos">
        <div ng-controller="meusCursosController as meusCursos">
            <ul>        
                <p>{{ cursos.id }}</p>
                <p>{{ cursos.content }}</p>
            </ul>       
        </div>  
        <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.8/angular.min.js"></script><script>angular.module('appCursos',[]).controller("meusCursosController", ['$http', '$scope', function($http,$scope) {

            var baseUrl='http://rest-service.guides.spring.io/greeting';

            $http.get(baseUrl).then(function(result) {
                $scope.cursos = result.data;
            });

        }]);
        </script>
    </body>
</html>

You need to put both $ http and $ scope within the control.

Another alternative would be to not use $ scope and work with this to access / create attributes from / within the control itself:

var baseUrl = #...;
meusCursos = this;
meusCursos.cursos = [];
# ...
    meusCursos = result.data;
# ...

And then access them in HTML as meusCursos.cursos.id and meusCursos.cursos.content .

    
07.04.2018 / 16:50