skip to content
Alvin Lucillo

RxJS to fetch data

/ 2 min read

💻 Tech

RxJS can be used in Angular to subscribe to asynchronous data. This can be done by subscribing to an Observable object. For example, HttpClient has a get function that returns an Observable like the code below. It receives a URL to call the API then returns an Observable of type any.

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'https://api.github.com/users/someuser';

  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get<any>(this.apiUrl);
  }
}

App component calls getData() from the data service and receives an Observable, which is a concept in RxJS that represents stream of data that can be observed. It doesn’t have the data or call the API until something subscribes to it. When the code subscribes to it, it has three callbacks: next, error, and complete. next receives the next stream of data, error receives any error that occurred, and complete is called when emission of values are completed.

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `
    <div *ngIf="data">
      <pre>{{ data | json }}</pre>
    </div>
    <div *ngIf="error">
      <p>Error: {{ error }}</p>
    </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data: any;
  error: string = '';

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe({
      next: (response) => {
        this.data = response;
      },
      error: (err) => {
        this.error = err.message;
      },
      complete: () => {
        console.log('Data fetching completed');
      }
    });
  }
}