Blog>
Snippets

Effective Use of RxJS Observable with Angular Components

Show an example of integrating RxJS observables with Angular for efficient data stream management.
import { Observable } from 'rxjs';
import { Component, OnDestroy } from '@angular/core';
import { DataService } from './data.service'; // hypothetical service

@Component({
  selector: 'app-observable-example',
  template: `
    <h1>Data List</h1>
    <ul>
      <li *ngFor="let item of dataList">{{ item }}</li>
    </ul>
  `,
})
export class ObservableExampleComponent implements OnDestroy {
  dataList: any[] = [];
  private dataSubscription: any;

  constructor(private dataService: DataService) {
    // Subscribe to the observable provided by the service
    this.dataSubscription = this.dataService.getDataStream().subscribe(
      data => {
        // Handle the incoming data
        this.dataList = data;
      },
      error => {
        // Handle the error case
        console.error('An error occurred:', error);
      }
    );
  }

  // Clean up the subscription to prevent memory leaks
  ngOnDestroy() {
    this.dataSubscription.unsubscribe();
  }
}
The provided code integrates an Angular component with an RxJS observable. The component subscribes to a data stream provided by a service (DataService) and updates the 'dataList' property with the incoming data. The subscription is established in the constructor and cleaned up in the 'ngOnDestroy' lifecycle hook to prevent memory leaks. This demonstrates efficient data stream management within an Angular component.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private dataUrl = 'api/data'; // URL to web API

  constructor(private http: HttpClient) {}

  getDataStream(): Observable<any[]> {
    // Returns an observable that emits data from a server endpoint
    return this.http.get<any[]>(this.dataUrl);
  }
}
This code creates a DataService class in Angular which provides an 'getDataStream' method that returns an RxJS Observable. The observable wraps an HTTP GET request to a specific URL ('api/data') for fetching data from a server. The Observable emits the server's response as an array of data items. The service can be injected into any component that requires a stream of data, such as the previous ObservableExampleComponent.