Angular HTTP Tutorial with RxJS Observables

The HTTP Module is deprecated by Angular. Please use the newer version of Angular HttpClient Tutorial

In this Angular HTTP tutorial with RxJs Observables, We learn how to use Angular HTTP Module to query the Remote API source to get data into our Application. We also learn how to Subscribe to the Returned response using RxJs observables.

We learned how to Build Components, creates and inject services, use pipes and directives to build Angular Application. But our app would not be useful without data. To get the data, we need send GET Request using the HTTP.

The source is now updated from Angular 2 to Angular 4.

Using HTTP in Angular

HTTP is a separate model in Angular and is available under the ‘@angular/http’ package. All you need to do is to import it, inject it into our component/service. Then, Use Get method to send an HTTP Request and subscribe to the response Asynchronously. And when the response arrives map it the desired object and displays the result.

Here are the steps in detail

Import HTTP Module in Root Module

We need to import it in our root module app.module. Also, we need to add it to the imports metadata array.

Import Required Module in Component/Service

Then you should import the required services in your component class as shown below

Inject HTTP service into your component/service

Call the HTTP Service

We send the get request to our Service API endpoint. The HTTP method returns an Observable, which is subscribed. When the result arrives it is converted to the data and displayed to the user.

That’s it.

Notice that when we use Angular HTTP Services to get data, it actually returns an Observables.

What is Observable?

Observable help us to manage async data. You can think of Observables as an array of items, which arrive asynchronously over time.

The observables implement the observer design pattern, where observables maintains a list of dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods

Observer subscribes to an Observable. The observer reacts when the value of the Observable changes. An Observable can have multiple subscribers and all the subscribers are notified when the state of the Observable changes.

The Observables are used extensively in Angular. The new HTTP service and Event system are all Observable based.

The Observables are Proposed Feature for the next version of Javascript. The Angular  Uses Third party library called Reactive Extensions or RxJs to implement the Observables. You can learn about RxJs from these RxJx tutorials

Observables Operators

Operators are methods that operate on an Observable and return an observable. Each Operator modifies the value it receives. These operators are applied one after the other in a chain.

RxJs Provides several Operators, which allows you to filter, select, transform, combine and compose Observables. Examples of Operators are map, filter, take, merge etc

How to use RxJs

RxJs is a very large library. Hence Angular exposes a stripped down version of Observables. You can import it using the following import statement

The above import imports only the necessary features. It does not include any of the Operators.

To use observables operators, you need to import them as shown below

Angular HTTP Tutorial

Now, We have a basic understanding of HTTP Service & observables, let us build an HTTP Service.

The source code for this tutorial is available at GitHub. The Start folder contains the initial code and the final code is in the HTTP folder

Let us query the GitHub repository to get the details of the repositories for a selected user.

Repository Model

Create repos.ts file and add the following code. This is a simplified model for GitHub repository.

GitHub Service

Create githubservice.ts and add the following code

First, we import required HTTP libraries from ‘@angular/http’ package.

Observable is included from the RxJs library. Our GetRepos method needs map & catch RxJs Operator. Hence we import it.

GetRepos Method

The GetRepos method, which calls the http.get method is shown below

The getRepos method takes userName as the argument and returns an observable of Repos.

Calling the API Endpoint

The first step is to call the get method passing the API endpoint as shown below

The get method does not return the response, but it returns an observable<response>.

Transform the returned object

We can return the response back to the component. But our component requires the list of Repositories and not the response object. Hence we need to transform the response object to list of Repositories. That is where the map operator comes in.

Map method transforms the items emitted by an Observable by applying a function to each.

We are calling the extractRepos from the map method to transform the data from the response to the repos[]. All we need to do is cast response.json to the repos[] and then returning it back.

The above code could have written using the arrow syntax as shown below

Handle the Error

We need to handle the error. The Observable has a catch method which is called, whenever there is any error.

We are calling the handleError from the catch operator. You can use the handleError method to create a user-friendly message, log the error to the console etc.

Component

Add the following code to app.component.ts

We are using Dependency injection to inject our newly created gitHubService into the component.

We have four variables.

userName: GitHub username
Repos: variable to hold the data received from GitHub
Loading: to display the loading indicator to the user
errorMessage: to display the user-friendly error message

GetRepos method

We make a call to GetRepos to retrieve the Repos.

We start with initializing loading to true so that we can display a loading indicator to the user.

We, then make a call to the getRepos method of the gitHubService, with the userName.

This method returns Observable<repos>. We then subscribe to it.

Subscribe method

The Subscribe operator is the glue that connects an observer to an Observable

We need to Subscribe to an observable to see the results of observables.

The subscribe method has three arguments. Each specifies the action to be taken when a particular event occurs

Success: This event is raised whenever observable returns a value. We use this event to assign the response to the repos

Failure: This event occurs, when observable is failed to generate the expected data or has encountered some other error. The error message is assigned to the local variable errorMessage so as to display the result to the user. The loading indicator is also disabled as the observable now terminates due to the error

Completed: This event fires, when the observables complete its task. We disable the loading indicator here.

Template

The input box asks for the GitHub userName. Two-way binding is used here to map it the userName in the component class.

A button binds to the click event to make a call to getRepos method on the Component

The loading Indicator using the ngIf directive to hide or show the “loading …” message

The error messages are displayed to the user only if they are present. Again using the ngIf Directive

Finally, we display the list of GitHub Repos using the ngFor Directive

Inspect the received data using the Json pipe

Module

Finally, we need to make few changes in our root Module (appModule)

We need to import the GitHubService

And register it with the Providers array. This will make the service singleton and can be injected via dependency injection

Finally, you can run the code.

You can test the error message by making the Url invalid.

Conclusion

We learned how to create a simple HTTP Service in this tutorial. We also looked at basics of Observables which is not extensively used in Angular

You can download the source code from this link

2 thoughts on “Angular HTTP Tutorial with RxJS Observables”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top