HTTP requst via service and unsubscribe from Observable

May 28, 2021 · 1 min readLucian Ciobanu
Tags:Angular

As Angular makes a serious destinction between view, component and services, I find it important to clarify the process and have it written down.

In the component which needs the data, import the service and inject it in the constructor; I also add a subscription array so that I will unsubcribe from the observables OnDestroy and prevent data leakage.

import { ComponentService } from '../component.service';
import { Subscription } from 'rxjs';

export class Component implements OnDestroy {
  priavate subscriptions: Subscription[] = [];
  constructor(private componentService: ComponentService) {}

  ngOnInit(): void {
    this.getData();
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(subscription => {
      subscription.unsubscribe();
    });
  }
  
  private getData() {
    const data = this.componentService.subscribe(
      receivedData => console.log(receivedData)
    );
    this.subscriptions.push(data);
  }

Cheers,
Lucian

Picture of author

Web Development & Software Delivery