Codementor Events

Fetching Data from an API

Published Aug 23, 2016Last updated Jan 18, 2017
Fetching Data from an API

For simple backend interactions, the $http module lets us do simple HTTP calls to an API end point. $http can be used for small, one-off HTTP requests. The $http service is a core Angular service that facilitates communication with the remote HTTP servers, via the browser's XMLHttpRequest object or via JSONP.


DIRECTIONS

  • Create the HttpService service in app.js with a function getPost that will make an $http call to get a post:
.controller('AppCtrl', function($scope) {
})

.service('HttpService', function($http) {
  return {
    getPost: function() {
      // $http returns a promise, which has a then function, which also returns a promise.
      return $http.get('http://jsonplaceholder.typicode.com/posts/1')
       .then(function (response) {
       // In the response, resp.data contains the result. Check the console to see all of the data returned.
       console.log('Get Post', response);
       return response.data;
      });
    }
  };
});

The $http service is a function that takes a single argument — a configuration object — which is used to generate an HTTP request and returns a promise. The JSON server at jsonplaceholder.com will return a single post. You can see this response in the browser by going to the URL http://jsonplaceholder.typicode.com/posts/1.

  • Inject HttpService in the AppCtrl controller:
.controller('AppCtrl', function($scope, HttpService) {
  • Call the getPost function from the AppCtrl controller in order to set the response on the scope:
.controller('AppCtrl', function($scope, HttpService) {
  HttpService.getPost()
    .then(function(response) {
    $scope.post = response;
  });
})
  • Add <div> to include an {{ post.title }}, which shows the response:
<div>
  The only post returned is {{ post.title }}
</div>

If you change {{ post.title }} to {{ post }}, you will see everything returned by the JSON object.

  • Add a function that gets users from a sample API to the HttpService:
.service('HttpService', function($http) {
  return {
    getPost: function() {
      // $http returns a promise, which has a then function, which also returns a promise.
      return $http.get('http://jsonplaceholder.typicode.com/posts/1')
        .then(function (response) {
        // In the response, resp.data contains the result. Check the console to see all of the data returned.
        console.log('Get Post', response);
        return response.data;
      });
    },
    getUsers: function() {
      // $http returns a promise, which has a then function, which also returns a promise.
      return $http.get('http://jsonplaceholder.typicode.com/users')
        .then(function(response) {
        // In the response, resp.data contains the result. Check the console to see all of the data returned.
        console.log('Get Users', response);
        return response.data;
      });
    }
  }
});
  • Call the getUsers function in the AppCtrl controller after the getPost function call:
HttpService.getPost()
  .then(function(response) {
   $scope.post = response;
 });

HttpService.getUsers()
  .then(function(response) {
   $scope.users = response;
 });

Notice that not much is different between this call and the previous one. The only differences are: The file path we are calling, the response is returned as an array, and the variable we are storing the response in is called users. You can also view this response in the browser by opening the URL http://jsonplaceholder.typicode.com/users.

  • Add the following <li> in the <ul>:
<div>
  The only post returned is {{ post.title }}
</div>
<ul>
  <li ng-repeat="user in users">
    {{ user }}
  </li>
</ul>

We're looping through the response using ng-repeat, so each user in the array will be displayed as an <li> in the list.

  • Break the item into separate lines to mimic a contact list:
<li ng-repeat="user in users">
  Username: {{ user.username }}<br>
  Name: {{ user.name }}<br>
  Email: {{ user.email }}<br>
  Website: {{ user.website }}<br>
</li>

As you can see, you don't have to display all of the properties in the user object. You can choose what to display and customize it for your use case.

Other tutorials you might be interested in:

Discover and read more posts from Sasha
get started
post commentsBe the first to share your opinion
Show more replies