Make HTTP Requests In An Ionic 2 Android And iOS App

Anyone looking to build a mobile application is going to find themselves needing to make HTTP requests to some remote web service at some time.  It is just how the modern web and modern app development process is now.  Previously I had demonstrated how to make HTTP requests in an Ionic Framework 1 application, but since Ionic 2 is all the rage right now, we’re going to switch gears and see how it is done in the latest framework version.

The bulk of this tutorial will be demonstrating how to make these web service requests in Angular 2 since it is fairly different from the first AngularJS version.

Let’s work on an actual Ionic 2 example.  Start by creating a fresh project from your Terminal (Mac and Linux) or Command Prompt (Windows) like so:

A few things to note about project creation.  If you’re not using a Mac you won’t be able to add and build for the iOS platform.  You’ll also need to be using the Ionic CLI that supports Ionic 2 applications.

We won’t be using any Apache Cordova plugins in this example so we can jump right into our project.   However, first let’s determine which HTTP service we are going to test against.  A convenient service, httpbin, allows for testing web requests.

We’re going to make GET requests against https://httpbin.org/ip and POST requests against https://httpbin.org/post.

This application will be simple.  It will have two buttons, one for GET requests and one for POST requests.  Starting with the app/pages/home/home.js file, change the code to look like the following:

A few important things going on here.

First we are importing Angular 2’s HTTP dependency.  With it imported we can set it in our constructor so it can be used in our other two functions.  The constructor runs when the page loads.

The UI view to compliment this logic can be found in the app/pages/home/home.html file.  Open it and change the code to look like the following:

Nothing fancy in this UI file.

Ionic 2 HTTP GET Request Ionic 2 HTTP POST Request

The GET request will show an alert with the requestors IP and the POST request will show an alert with the body data sent.

For reference, an Angular 2 POST with “the works” might look like this:

You can include a POST body and specific headers to the request.

Conclusion

We just saw how to make HTTP requests using Ionic 2.  Although similar to making HTTP requests with Ionic Framework 1, how Angular 2 does things is a little different.  These requests are a necessity when working with web service APIs like, but not limited to, Google and Facebook.

Nic Raboy

Nic is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, GoLang, NativeScript, and Unity3D.

  • Rich Brewer

    Thanks for another great tutorial Nic.

    Two items:

    It looks like you’ve got an extra comma in the Page decorator (at the end of line 5 in www/app/home/home.js) – don’t know if it’s really a problem, but thought I’d mention it.
    More importantly, for me at least, when I emulate the app with $ ionic serve, I get a blank page and browser console error:

    Do you have any advice for correcting?

    • My guess is that ionic serve is your problem here. I can’t say I recommend ever using it.

      What happens when you build and install on the device or simulator?

      • Rich Brewer

        Hmmm, blank screen on device too.

        Here is more detailed chrome console verbiage:

        As an aside, you mention that you don’t trust ionic serve. It’s very convenient though. What’s your development workflow; write, save, build, install, assess, repeat? I’m new to app development and the thought of a two plus minute round trip to assess my (quite lame noob) code kind of freaks me out.

        • Ionic serve screws with the way apps are run which I’ve found to be more negative than positive. It is convenient, but you shouldn’t sacrifice quality for convenience.

          I write, compile, install, repeat. Takes a bit of time, but it’s worth it.

          Are you doing a TypeScript project or JavaScript?

          • Rich Brewer

            JavaScript. I’ve really struggled to get my ionic dev environment set up this far (getting nodejs working without sudo, getting Android sdk installed in a way that works with ionic, …) so I’ve avoided the added complexity of typescript even though I gather that it provides benefits – perhaps the compile step would give some insight into the exception I’m getting in the tutorial?

          • Should be fine. What version of the Ionic CLI are you using? Run ionic info and let me know everything it returns.

          • Rich Brewer

            From ionic info:

          • I think the problem is that you’re using Node 5.x. I could be wrong, but I think anything greater than 4 is unsupported. I personally use 0.12 since 4 is even unsupported in a lot of what I do.

            Maybe start there?

            BTW, you’re going to have a rough time downgrading Node.

          • Rich Brewer

            Managed to move to

            but still same error.
            The error seems to point to trouble with the Popup component, so I guess I’ll try to create a version of the tutorial that uses a different component – keeping everything else the same. I’ll let you know what comes of it.

          • Seems like you should be good. Report back if you figure it out in case others have the same problem.

            Best,

  • Thomas Degroot

    Thanks Great tutorial, one thing I think would be important is timeout function. I have not seen a working example of this yet.

  • Dipak Mahapurkar

    Thanks for great tutorial. but i got some error my log is:

    EXCEPTION: Cannot resolve all parameters for ‘HomePage'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that ‘HomePage’ is decorated with Injectable.

    app.bundle.js:32027 EXCEPTION: Cannot resolve all parameters for ‘HomePage'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that ‘HomePage’ is decorated with Injectable.BrowserDomAdapter.logError @ app.bundle.js:32027BrowserDomAdapter.logGroup @ app.bundle.js:32037ExceptionHandler.call @ app.bundle.js:7805(anonymous function) @ app.bundle.js:16903NgZone._notifyOnError @ app.bundle.js:17544collection_1.StringMapWrapper.merge.onError @ app.bundle.js:17439run @ app.bundle.js:1186(anonymous function) @ app.bundle.js:17457zoneBoundFn @ app.bundle.js:1156lib$es6$promise$$internal$$tryCatch @ app.bundle.js:2556lib$es6$promise$$internal$$invokeCallback @ app.bundle.js:2568lib$es6$promise$$internal$$publish @ app.bundle.js:2539(anonymous function) @ app.bundle.js:1288microtask @ app.bundle.js:17497run @ app.bundle.js:1183(anonymous function) @ app.bundle.js:17457zoneBoundFn @ app.bundle.js:1156lib$es6$promise$asap$$flush @ app.bundle.js:2350

    app.bundle.js:32027 STACKTRACE:BrowserDomAdapter.logError @ app.bundle.js:32027ExceptionHandler.call @ app.bundle.js:7807(anonymous function) @ app.bundle.js:16903NgZone._notifyOnError @ app.bundle.js:17544collection_1.StringMapWrapper.merge.onError @ app.bundle.js:17439run @ app.bundle.js:1186(anonymous function) @ app.bundle.js:17457zoneBoundFn @ app.bundle.js:1156lib$es6$promise$$internal$$tryCatch @ app.bundle.js:2556lib$es6$promise$$internal$$invokeCallback @ app.bundle.js:2568lib$es6$promise$$internal$$publish @ app.bundle.js:2539(anonymous function) @ app.bundle.js:1288microtask @ app.bundle.js:17497run @ app.bundle.js:1183(anonymous function) @ app.bundle.js:17457zoneBoundFn @ app.bundle.js:1156lib$es6$promise$asap$$flush @ app.bundle.js:2350

    app.bundle.js:32027 Error: Cannot resolve all parameters for ‘HomePage'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that ‘HomePage’ is decorated with Injectable.

    how to resolve it?
    Thanks !!!

    • Popup was changed to alert. Check for changes that I made.

  • Fábio Burkard

    Nice tutorial! It’s not easy to find material about the new Angular 2 + Ionic 2, at least till now…

    I’m having two errors (in each call – get or post); the first is

    2 288437 group EXCEPTION: TypeError: error.json is not a function

    Ok, if I remove the () from error.json, on lines 24 and 38, it doesn’t throw an Exception, but I can’t reach the remote server.

    I tried disabling firewall – no success…tried on “ionic serve -c” and on a real device, no success too…

    I can’t see where is the problem – my suspect was the Http module, but it doesn’t throw error on the console when importing…

    Could you please, give a clue? =)

    Btw, excellent blog!

    • So I’m wondering if the Angular 2 Http module changed yet again on me. Wouldn’t be the first time.

      You definitely do not want to do console.log(error.json). That isn’t right. If error.json() isn’t working for you, you can always do console.log(error).

      On a side note, I don’t ever recommend using Ionic Serve. I have a blog post coming out in a few days on the subject. Your life will be better off if you kill that bad habit.

      Let me know what happens.

      Best,

      • Fábio Burkard

        Got it… in 1st line, I should have also imported “Alert”…
        import {Page, Alert, NavController} from ‘ionic/ionic’;

        That’s all… Thanks for the quick reply!

        • Thanks for pointing out my mistake. I’ve corrected it in the post.

          Best,

  • Luke

    Nic, can you do an example where you make the http request from a service? The service could process the data (like store a token for a user model) and then pass the data to a page.

  • Leonardo Mendonça Piazzoli

    The link “FOLLOW ME: YouTube” it is incorrect.

  • Leonardo Mendonça Piazzoli

    The link “FOLLOW ME: YouTube” it is incorrect.

    • Fixed it. Thanks for letting me know!

  • Razaleigh Wiseman

    Hi, I got error “Unexpected token while parsing file” whenever I run ionic serve. Is there any additional code to be added? thanks

  • Hi Nic .. when error occured why finally never get fired? is this expected behaviour? example i want to hide loading modal after make http request, so right now i put my loading.dismiss() inside success and error callback

    Thanks

    • I’m not quite sure what you’re asking. I believe there is a language barrier. Can you please try again?

      • Hi ..

        I mean, when observer return error, then “finally” callback is never gets fired .. its fired only when observer return data or success.. is this expected behavior?

  • Jagannath Rao

    Could you attach the entire project here pls ?

    • Sorry, I only provide the full projects with my paid content. It is incentive for people to support the work I do.

      Best,

  • Jose Pablo Brotons

    Hi Nic, when I try to get, this error comes out with Ionic serve, i need to see the log that’s why I am using Ionic serve. Do you know what’s this error about? https://uploads.disquscdn.com/images/e33cb14cb97a67d05f9bdb8de5451025b6a5013f76244206eb796990427c62bc.jpg

    • It is a cross origin resource sharing (CORS) error. You’re receiving it because you’re trying to access an API via JavaScript, from a different host. This is a common problem when using Ionic Serve. These CORS errors don’t happen when running directly from the device.

      I encourage you to not depend so much on Ionic Serve. If you need to see the error logs, deploy to an Android device or simulator and run adb logcat from the Terminal. It will spit out your logs as they happen.

      Best,

  • Mahendra

    Hi sir, i have some problem in http get request in angular2 ionic2 framework.i am not able to do this please guide me with proper code.