⚠️ This lesson is retired and might contain outdated information.

Fetch data from an API using Angular 2 HTTP module

Mike Hartington
InstructorMike Hartington
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 months ago

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

[00:01] 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.

[00:18] 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.

[00:37] 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.

[00:53] 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.

[01:16] 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.

[01:29] 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.

Jeff Richardson
Jeff Richardson
~ 7 years ago

I seem to be stuck on this lesson. Http must be defined along with several other providers. Anyone else run into this and have a solution?

Gavin
Gavin
~ 7 years ago

I seem to be stuck on this lesson. Http must be defined along with several other providers. Anyone else run into this and have a solution?

I had the same problem but found that I did need to import HttpModule in the app.modules.ts file. import { HttpModule } from '@angular/http';

And then added HttpModule to the imports below.

It all worked after I did that.

Markdown supported.
Become a member to join the discussionEnroll Today