Fetching data in Angular: HttpClient or Fetch API?

Most angular developers use Angular's HttpClient class to fetch data from a rest API in a data service. Not only this class requires you to add RxJS as a dependency to your project, you also need to set up a provider for HttpClientModule in your app.config.ts. Your data service often looks like this:

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

interface User {
  firstname: string;
  lastname: string;
  birthday: string;
  id: string;
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'https://6561036783aba11d99d1cff0.mockapi.io/api/test';

  constructor(private http: HttpClient) {}

  getData(): Observable<User> {
      const users = this.http.get<User>(this.apiUrl);
      return users;
  }
}

Then you use it in your component like this:

export class MyComponent {
  constructor(private dataService: DataService) {}

  logData() {
    this.dataService.getData().subscribe(data => console.log(data));
  }
}

However since Rest APIs rely on HTTP it means you always get one response per request, so there is really no need to use an Observable and you can achieve the same result using JavaScript's Promises by using Fetch. Here is DataService written using promises rather than observables:

import { Injectable } from '@angular/core';

interface User {
  firstname: string;
  lastname: string;
  birthday: string;
  id: string;
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'https://6561036783aba11d99d1cff0.mockapi.io/api/test';

  getData(): Promise<User> {
      const users = fetch(this.apiUrl).then(res => res.json());
      return users;
  }
}

And you use it in your component like this:

export class MyComponent {
  constructor(private dataService: DataService) {}

  logData() {
    this.dataService.getData().then(data => console.log(data));
  }
}

As you see we no longer need to import HttpClient and Observable classes and the code is more reusable since it can be used in any other framework or even without a framework.