Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Fetch data from an API using Angular 2 HTTP module

    Mike HartingtonMike Hartington
    2 - 6

    A typical app will interact with some sort of remote API at some point. We’ll creating a simple provider class to fetch data from the Random User API and populate our apps UI with this data.

    The IonicModule in this lesson provides some default Angular modules for convenience. As of Ionic 2.x.x, those modules include Angular's BrowserModule, HttpModule, FormsModule, and ReactiveFormsModule



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Returning static data is fine, but it would be even better if we could return actual data from an API. Since our current people array is based off the random user API, let's use that. We'll modify the Get People method and have it return the results from an HTTP request.

    We'll say, this.http.get, and then we'll paste in the URL for the random user API, along with a query parameter to return three users. We'll then use map from RxJS and return the results of this request as .json. Save our file.

    Since we haven't updated the home page class yet, you'll notice we'll get a nice runtime error report from Ionic. Let's edit home.js and modify how we're loading our data. We'll modify our property of people and set it to an empty array for now.

    Then, down in the constructor, we'll make the call to the API with this.service.getpeople. Since HTTP is an observable, we'll subscribe to the requests and then set this.people to equal the data that gets returned from the request.

    We'll save our file, and then all of our data will get loaded through our request to the API. Now, something that you may have noticed is that we did not need to include the HTTP module inside of our app's main ngModule.

    This is because the Ionic module already provides this for you. It also includes the FormsModule and the ReactiveFormsModule, as one or the other is expected to be used to some capacity.