Create HTTP Observable from Fetch in Angular

Angular is a popular front-end framework for building web applications. One of the essential aspects of web development is making HTTP requests to fetch data from a server or send data to it. Angular provides a powerful HttpClient module for this purpose, but you can also use the Fetch API to create HTTP observables. In this blog post, we will explore how to create HTTP observables from the Fetch API in Angular.

Understanding HTTP Observables

Before we dive into the details of creating HTTP observables from the Fetch API, let’s briefly understand what HTTP observables are. In Angular, HTTP observables are used to manage asynchronous HTTP requests. They are a crucial part of modern web development, as they allow us to work with data from APIs, servers, or other sources asynchronously.

Angular provides an HttpClient module that simplifies making HTTP requests. However, the Fetch API is another way to perform HTTP requests in a more low-level manner.

Using the Fetch API

The Fetch API is a modern web API for making network requests. It provides a cleaner and more modern alternative to the older XMLHttpRequest. To use the Fetch API in Angular, follow these steps:

Step 1: Import the Required Modules

First, you need to import the Observable class and other necessary modules. In your Angular component, include the following imports:

import { Observable, from } from 'rxjs';
import { map } from 'rxjs/operators';

Step 2: Create an HTTP Observable with Fetch

Now, you can create an HTTP Observable using the Fetch API. Here’s an example of how to fetch data from an API and convert it into an Observable:

const url = 'https://api.example.com/data';

const fetchData = () => {
  return from(fetch(url))
    .pipe(
      map(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
    );
};

const dataObservable: Observable<any> = fetchData();

In this code, we use the fetch function to make an HTTP request and then use the from operator from RxJS to convert the Promise returned by fetch into an Observable. We also use the map operator to handle the response and convert it to JSON.

Step 3: Subscribe and Handle the Data

To consume the data from the created Observable, you can subscribe to it in your Angular component:

dataObservable.subscribe(data => {
  console.log('Received data:', data);
}, error => {
  console.error('An error occurred:', error);
});

This code subscribes to the dataObservable and logs the received data or any errors that occur during the HTTP request.

Create Http Observables

Now, that we understand how to use Fetch API with observables. Let’s create a utility (re-usable) function which creates Http Observables when needed.

import { Observable } from 'rxjs';

// Below function makes use of create method to create an Observable
export function createHttpObservable(url: string): Observable<any> {
    return  Observable.create(observer => {

      // AbortController for cancelling our subscriptions when needed.
      const controller = new AbortController();
      const signal = controller.signal;

      fetch(url, {signal})
        .then(response => {
          return response.json();
        })
        .then(body => {
          observer.next(body);
          observer.complete();
        })
        .catch(err => {
          observer.error(err);
        });

        return () => controller.abort();
    });
  }

Use the utility function like below:

this.myData$ = createHttpObservable('api/dataItems');
Benefits of Using Fetch with Observables

Using the Fetch API with Observables in Angular offers several advantages:

  • Flexibility: The Fetch API provides a simple and flexible way to make HTTP requests, allowing you to customize the request headers and other options.
  • Observables: By converting the Fetch API’s Promise into an Observable, you can leverage RxJS operators to work with the asynchronous data flow effectively.
  • Error Handling: You can easily handle errors using RxJS operators like catchError, making your code more robust.
  • Interoperability: Fetch works well with other web APIs and libraries, so you can integrate it with various third-party services seamlessly.
Conclusion

While Angular’s HttpClient module is a powerful tool for making HTTP requests, the Fetch API offers an alternative approach for those who prefer a more low-level control over their requests. By converting Fetch API responses into HTTP observables, you can leverage the power of RxJS operators for efficient data handling in your Angular applications.

Remember that the choice between HttpClient and Fetch API depends on your specific use case and requirements. Both are valid options, and you should choose the one that best fits your project’s needs.

Happy coding!

Published by Kumar Gandhi K

Hi! I’m Kumar and I live in Bangalore (IN) with my family. By profession I’m a Web Developer experienced in a vast variety of frameworks and technologies, like, HTML, CSS, JavaScript, Angular, Bootstrap… Using these i have built or sometimes maintained mid market and enterprise level applications. I worked for few software companies over the years and on few domains like finance, field-service and storage. I also did consulting job at one point. I am loyal and hard (or for better word smart) working individual. In my free time I read books, in fact I buy a lot of books hoping that some day I might find all the time in the world to read them and I also enjoy watching TV.

One thought on “Create HTTP Observable from Fetch in Angular

Leave a comment