Working with RxJS in Angular HTTP

Tutorial 3 of 5

1. Introduction

In this tutorial, we will be exploring the use of RxJS with Angular's HttpClient. RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables, making it easier to compose asynchronous or callback-based code. Angular's HttpClient makes use of these Observables for handling HTTP requests and responses.

By the end of this tutorial, you will:
- Understand the basics of RxJS and Observables
- Learn how to use RxJS with Angular's HttpClient to handle HTTP requests
- Handle asynchronous data streams effectively with RxJS

Prerequisites:
- Basic understanding of Angular and TypeScript
- Familiarity with HTTP protocols, AJAX, and JSON

2. Step-by-Step Guide

RxJS operates with Observables, which handle streams of events. A HTTP request, for example, is an event. Angular's HttpClient methods return RxJS Observables.

Creating an Observable

First, we will create an Observable. This will simulate a HTTP request.

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
  subscriber.complete();
});

observable.subscribe(val => console.log(val));

The Observable constructor takes a callback function that has a subscriber as a parameter. Inside this callback, we can call subscriber.next() to emit some values, and subscriber.complete() to signal that no more values will be emitted.

Making HTTP Requests

Angular's HttpClient returns an Observable whenever a HTTP method is called. We can subscribe to this Observable to handle the response.

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getData() {
  this.http.get('url').subscribe(data => console.log(data));
}

3. Code Examples

Making a HTTP GET Request

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

constructor(private http: HttpClient) {}

getData(): Observable<any> {
  return this.http.get('http://jsonplaceholder.typicode.com/posts');
}

// Usage
this.getData().subscribe(data => console.log(data));

We are creating a getData method that makes a GET request to a URL and returns an Observable.

Making a HTTP POST Request

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

constructor(private http: HttpClient) {}

postData(data: any): Observable<any> {
  return this.http.post('http://jsonplaceholder.typicode.com/posts', data);
}

// Usage
const data = { title: 'foo', body: 'bar', userId: 1 };
this.postData(data).subscribe(response => console.log(response));

For a POST request, we pass in the data as the second argument to http.post().

4. Summary

In this tutorial, we have learned how to use RxJS with Angular's HttpClient. We have learned how to create Observables and how to make HTTP requests using HttpClient, which returns Observables.

For further learning, explore error handling in RxJS and HttpClient, and how to use other RxJS operators to transform the data returned by HttpClient.

5. Practice Exercises

  1. Make a HTTP DELETE request using HttpClient. Print the response to the console.
  2. Make a HTTP PUT request using HttpClient. The request should update a resource on the server. Print the response to the console.

Solutions:
1.

this.http.delete('http://jsonplaceholder.typicode.com/posts/1')
  .subscribe(response => console.log(response));
const data = { id: 1, title: 'foo', body: 'bar', userId: 1 };
this.http.put('http://jsonplaceholder.typicode.com/posts/1', data)
  .subscribe(response => console.log(response));

In the DELETE request, we don't need to send any data, just the URL to the resource. In the PUT request, we send the data to update the resource.