As a modern developer, at some point in time you’re going to find yourself needing to work with a RESTful API. You’re going to need to make HTTP requests to get data into your app or even change data on a remote database.
Lucky for us, making HTTP requests with Ionic Framework is a heck of a lot easier than making them with native code.
The following will show you how to make GET requests for JSON data at some fictional API endpoint. It is for Ionic Framework 1. If you’re looking for how to make HTTP requests using Ionic 2, check here.
In AngularJS you can use the $http service to make requests. The following is an example of how to use the $http
service:
$http.get("http://localhost/example.json", { params: { "key1": "value1", "key2": "value2" } })
.success(function(data) {
alert("SUCCESS!");
})
.error(function(data) {
alert("ERROR");
});
Lucky for us, we can use the same code in our Ionic project.
So lets go ahead and create a new Ionic project with the Android and iOS platforms:
ionic start ExampleProject blank
cd ExampleProject
ionic platform add android
ionic platform add ios
Just note that if you’re not on a Mac, you cannot add the iOS platform. Let’s go ahead and crack open the www/js/app.js file and create a new controller for our project:
exampleApp.controller('ExampleController', function($scope, $http) {
$scope.getData = function() {
$http.get("http://localhost/example.json", { params: { "key1": "value1", "key2": "value2" } })
.success(function(data) {
$scope.firstname = data.firstname;
$scope.lastname = data.lastname;
})
.error(function(data) {
alert("ERROR");
});
}
});
When you call the getData()
method from your HTML file it will make a GET request to our fictional RESTful endpoint passing a few parameters. If successful, we are expecting the data response to have a firstname
and lastname
element which we will store in our scope.
Some things to note when making HTTP requests with Ionic Framework or any JavaScript framework for that matter. You may run into issues with cross origin resource sharing (CORS) errors. There shouldn’t be an issue when testing your requests from the device, only from a browser. To resolve these browser errors, check out a previous article I made on the subject.
A video version of this article can be seen below.