How to make Http request and handle errors in Ionic Framework

In most of the cases in our mobile application we’ve to fetch data from a server. If you are using Ionic Framework, it’s not a big deal. Http plugin made it easy for us. Let’s see how to make http request in Ionic Framework using Http plugin to get data from server.

  1. Install the plugin: Run the following command in command line in your project:

    Add this module in providers array of your app.module.ts file:

Import the Http plugin:

Suppose we are going to use this plugin in HomePage.ts file. First we have to import the plugin and add it in constructor as argument:

GET request:

It is comparatively easy to make a GET request. So let’s do it first. ┬áJust write the following code in the method of your home page:

Here you have to change the example url to your server’s url. After receiving the data from server, you can get it in server_data variable.

POST Request:

Everything is same as GET request. Here you have to add header values and post parameters before performing the request. In most of the cases, header values are same as above. Just change postParams as per your data.

Error Handling:

I was working on an ionic project for a while that sends request to server to fetch data. I faced a problem while working on it. If there is no internet connection my busy dialog keeps loading and no error message occurs. Because, the Http GET or POST methods didn’t have any handler to control the errors. After searching for a while I didn’t find any solution on internet. Finally I found it myself. Let me share it with you.

Here I’ve added error handler in subscribe section. Whenever a problem occurs, you can get the error message inside error section.