|

How To Make HTTP Requests In Angular Using Observables

angular http observables

To fetch data in Angular, we can use Observables with http to fetch data. An angular application will use http via a GET request to fetch data from a back-end server. The back-end could be powered by any number of server-side technologies such as Java, PHP, Python, or even server-side JavaScript in the form of Node.js. An http response is sent from the back-end web service to the client side angular application. In this tutorial, we’ll learn about things like Observables, Reactive Extensions, HTTP Requests, and how they integrate into an angular application.


Observables and Reactive Extensions

Reactive Extensions, or RxJS, represent a data sequence as an Observable Sequence. The Observable Sequence is simply referred to as an Observable. The purpose of an Observable is to manage asynchronous data, such as what you might get when waiting for data to arrive over a network using HTTP. An Observable treats events as a collection. One way to think of an Observable is that of an array whose items populate asynchronously over time. In an Observable, you would have a method that subscribes to receive notifications as new data arrives. The Angular framework uses Observables to do its asynchronous work.


Angular Observables

Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values. Observables are declarative—that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it.


Observable Operators

Function like map, filter, take, and merge are examples of observable operators. They transform the source observable and compose a new observable while processing each value as it is emitted. One way to better understand Observables is to become familiar with Marble Diagrams. Here, we see an example of the map function which transforms each value to 10 times its original state.
rx observable of map function


How to compose Observable Operators

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

The output for this in the console would be the following:

0

6

12

18

So what happens in the code above? Well first we import two common packages when working with Observables. Those are the rxjs and rxjs/operators packages. Then, the line of const source$: Observable<number> = range(0, 10) creates an observable stream of numbers in the range of 0 to 10. Note the dollar sign suffix which indicates that a particular variable is holding an Observable. For any variable now holding an observable, note that we can now use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection. So this example takes each number in the range of 0 thru 10, and multiplies it by 2. Then, we use the filter function to filter the result down to only the odd numbers. Once that is complete, we subscribe to the observable and log out the result. Pretty cool!


Promises vs Observables

A Promise is used to handle a single event when an async operation completes or fails while an Observable is like a Stream and allows to pass zero or more events where the callback is called for each event. Here is a table that shows some of the differences.

Promise

Observable

Provides a single future value
Emits multiple values over time
Not Lazy
Lazy
Can not cancel
Able to cancel
Can use with map, filter, reduce, and other operators

Send HTTP Request in Angular

Now that we know a bit about Observables, let’s configure our games application to fetch the games data from an API.


Import HttpClientModule

First up, we need to import the HttpClientModule module into the application. We can do this in app.module.ts like so.


Use Http Client In Game Service

In the Angular Service Dependency Injection tutorial, we had hard-coded the games data into the game.service.ts file directly. Now, we can remove that data and update the service to make an HTTP request to a web server to fetch the data. Below we highlight the updated code where we import the modules we need, inject the http module into the constructor, set up an API url to send the request to, and define the getGames() and handleError() methods.


Configure Server Side API

For this demonstration, we are sending the HTTP request to http://lpg.io/api/angulargames which is a server running on a virtual machine. This server is using Laravel, a popular PHP framework that is very capable of providing dedicated JSON API web service features. Here is the code we use on the server-side using Laravel.


api.php

Note: You will also need to add the below snippets to \public\index.php to enable CORS functionality. If you do not include these, you may encounter errors such as Server returned code: 0, error message is: Http failure response for (unknown url): 0 Unknown Error or perhaps something like Access to XMLHttpRequest at ‘http://lpg.io/api/angulargames’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.


Update Game List Component

With everything now in place, we can update the game-list.component.ts file. Specifically, we will write new code for the ngOnInit() life cycle hook so that it now makes use of Observables to make an http get request to our api using our updated game service.

Our new Game Service which uses Observables to make an http request to a Laravel back-end server is now working!
angular http request via observable example

You can also see the API response data in the console section of chrome developer tools.
inpecting angular api response data in console


How To Make HTTP Requests In Angular Using Observables Summary

Here are some key points to remember when dealing with Observables and HTTP Requests in Angular.

Setting up HTTP in Angular

  • Add HttpClientModule to the imports array of one of the applications Angular Modules
  • Import what is needed for the data service
  • Define a dependency for the http client service using the constructor
  • Create a method for each http request type you would like to use
  • Call the http method(s) as needed (for example GET)
  • Use Generics to specify the return type

Subscribing To Observables

  • Call the subscribe method of the returned observable
  • Create a function to handle emitted items
  • Assign property data to returned JSON object
  • Create a function to handle errors
|