Getting data from a web service with Angular.js
Asked Answered
G

4

5

Im trying to get data in a Json format from a remote WS using Angular and im having some trouble. The data comes from the web service correctly but i cant use it inside the controller. Why is that? Angular Code:

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

// get data from the WS
app.run(function ($http) {
    $http.get("https://SOME_API_PATH").success(function (data) {
        booksJson = data;
        console.log(data);  //Working
    });
});

app.controller('booksCtrl', function ($scope) { 
    $scope.data = booksJson;
    console.log($scope.data); //NOT WORKING
});

HTML:

<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>
Gourmont answered 3/6, 2015 at 15:53 Comment(3)
using a run block? why not a .service which returns a promise? then just simply inject that service in your controller(s).Unrelenting
@ShehryarAbbasi Why should i use a service?Gourmont
@user4440845 You would use a service for many reasons. To name a few, dependency injection, modularity, maintainable, and provides a layer of abstraction. It depends though. If all you are ever going to do is receive a list of all books, then a service is overkill.Ommiad
A
16

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>
Aegisthus answered 3/6, 2015 at 16:12 Comment(2)
Nice answer. The .success method has now been depreciated. You should use the .then method now. docs.angularjs.org/api/ng/service/$httpPase
@BenCameron ok, thanks. I have updated the answer with that change now.Aegisthus
P
0

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.

Prehistory answered 3/6, 2015 at 16:5 Comment(0)
F
0

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;
    });
});
Farahfarand answered 3/6, 2015 at 16:9 Comment(0)
T
0
<!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>
Tricksy answered 18/2, 2016 at 11:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.