Ionic HTTP GET Json

ionic http get json

In this article we will customize the default generated Ionic app to fetch some JSON data from the remote API using HTTP GET-request.

At first, you should look again to a previous lesson were we used to learn how to generate a default Ionic project from “tabs” template. When you have it generated we can proceed to perform the customization.

Get Json data from HTTP request with Ionic

There are just 2 files that we need to change:

  • www/js/controllers.js
  • www/templates/tab-dash.html

Let’s start from the first file – controllers.js. There is a section for DashCtrl (Dashboard Controller) with an empty function. This is how it should be changed:

.controller('DashCtrl', function($scope, $http) {
  $scope.result = "";
  $http.get('http://date.jsontest.com/')
    .success(function(data, status, headers,config){
      console.log('data success');
      console.log(data); // for browser console
      $scope.result = data; // for UI
    })
    .error(function(data, status, headers,config){
      console.log('data error');
    })
    .then(function(result){
      things = result.data;
    });
})

The code above uses $http to send a GET request to API that returns the JSON for current date and time:

{
   "time": "09:53:53 PM",
   "milliseconds_since_epoch": 1458510833266,
   "date": "03-20-2016"
}

Now, all we need to do is to use the result data on the screen. Open tab-dash.html and replace its content with this:

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <h2>Ionic GET Json Example</h2>
    Current time: {{result.time}}
  </ion-content>
</ion-view>

As you can see, we refer to result’s time field using Angular expression language.

Now we need to run this code in browser or on your device.

To run in browser just execute this command in the project directory:

ionic serve localhost

You can see your app by typing http://localhost:8100.

To run on the device (in our case, Android platform):

ionic run android

And here is the result:

ionic http get result

Leave a Reply

11 Comments on "Ionic HTTP GET Json"


Guest
WELLINGTON TORREJAIS DA SILVA
7 months 3 days ago

Thanks!

Guest
edoardo
9 months 7 days ago

hi, i need to pass arrays from the server to the app.
how should i do?
Thank’s

Guest
aalfiann
9 months 15 days ago

awesome, it’s works for me.. But how if I want to get http json api using parameter? thanks

Guest
vbcabc
1 year 1 month ago

Hai for me also its giving data error response :( Could you please help me i am new to ionic and i gt frustrated of searching json

Guest
juan
1 year 2 months ago

hi i tried this tutorial but the url wont work, although y used another url I didnt recieved anything