Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from a web service with Angular.js

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>
like image 302
Vandervidi Avatar asked Jun 03 '15 15:06

Vandervidi


People also ask

How get data from AngularJS to HTML?

Create an app and its controller scope. Define the controller variable. Call the app and controller to the body of HTML. Inside the body use span tag and use attribute ng-bind-html and assign the value as the scope variable.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

How does angular connect to Web API?

Open Visual Studio >> File >> New >> Project >> Select Web Application. After that click OK and you will see the templates. Select the Web API template. Click OK.


1 Answers

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>
like image 93
Donal Avatar answered Sep 24 '22 17:09

Donal