Getting data from a web service with Angular.js

爷,独闯天下 提交于 2019-11-30 04:05:28

You should put your $http.get inside your controller.

Also, the web service returns an object not an array. So your ng-repeat should be something like this: book in data.books

Here is a working example:

var app = angular.module('booksInventoryApp', []);

app.controller('booksCtrl', function($scope, $http) {

  $http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
    .then(function(response) {
      $scope.data = response.data;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
  <section ng-controller="booksCtrl">
    <h2 ng-repeat="book in data.books">{{book.name}}</h2>    
  </section>
</article>

Create the bookJSON as array, and push the elements instead of assignment. So

var bookJSON=[];

Inside $http.get do

data.forEach(function(item) { bookJSON.push(item); });

The second console log will show undefined because, the call is async. The assignment happens in future.

The run method does not guarantee, that the code is run before controller loads.

There are other ways too to solve this issue.

Avoid global variable. Look at $routeProvider resolve property.

Or implement a service to get this data as promise.

Instead of using a run block you can use your $http service inside the controller, then attach your data to the scope like normal. Just remember to inject the $http service into your controller.

app.controller('booksCtrl', function ($scope, $http) { 
    $http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks").success(function (data) {
        $scope.booksJson = data;
    });
});
<!DOCTYPE html>
<html>
<head>
    <title>test your webservice</title>
</head>
<body>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
  <section ng-controller="booksCtrl">
  </section>
</article>
<script type="text/javascript">
    var app = angular.module('booksInventoryApp', []);

app.controller('booksCtrl', function($scope, $http) {



                        //ResponseInvocationAgentRequestDTO 
                        var jsonObject = {
                                      "id":65,
                                      "idUserSender": 5}


                                    console.log("aaaaaaaaaaaaaaaaaaaa");
            $http({
                method: 'put',             
                url: 'yout URI' ,
                data: jsonObject 
            })
            .success(function(data,status){
                console.log('all is good', data);

                })
                .error(function(data,status){
                    console.log('Erreur into url '+data);
                });


});

</script>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!