0
0
Angularframework~5 mins

Observable in component lifecycle in Angular

Choose your learning style9 modes available
Introduction

Observables help your Angular component get data that changes over time. They let your component react when new data arrives or when something updates.

When you want to get data from a server and update the view automatically.
When you need to listen to user input events like clicks or typing.
When you want to handle timers or intervals that update the UI.
When you want to clean up resources automatically when the component is removed.
When you want to react to changes in route parameters or query strings.
Syntax
Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-example',
  template: `{{ data }}`
})
export class ExampleComponent implements OnInit, OnDestroy {
  data: string = '';
  private subscription!: Subscription;

  ngOnInit() {
    const observable$: Observable<string> = new Observable(observer => {
      observer.next('Hello from Observable!');
      observer.complete();
    });

    this.subscription = observable$.subscribe(value => {
      this.data = value;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Use subscribe() to listen to Observable data.

Always unsubscribe in ngOnDestroy() to avoid memory leaks.

Examples
Subscribe to an Observable to get its data and update the component.
Angular
this.observable$.subscribe(value => {
  this.data = value;
});
Unsubscribe from the Observable when the component is destroyed to clean up.
Angular
ngOnDestroy() {
  this.subscription.unsubscribe();
}
Use interval Observable to update data every second.
Angular
import { interval } from 'rxjs';

ngOnInit() {
  this.subscription = interval(1000).subscribe(count => {
    this.data = `Seconds passed: ${count}`;
  });
}
Sample Program

This component shows a timer that updates every second. It uses an Observable from interval to emit numbers every 1000 milliseconds. The component subscribes to this Observable in ngOnInit and updates the message shown. When the component is removed, it unsubscribes to stop the timer and free resources.

Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-timer',
  template: `<p>{{ message }}</p>`
})
export class TimerComponent implements OnInit, OnDestroy {
  message: string = 'Starting timer...';
  private subscription!: Subscription;

  ngOnInit() {
    const seconds$ = interval(1000);
    this.subscription = seconds$.subscribe(sec => {
      this.message = `Seconds passed: ${sec}`;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
OutputSuccess
Important Notes

Observables can emit multiple values over time, unlike promises which emit once.

Always unsubscribe to prevent memory leaks, especially for long-lived Observables.

Angular's async pipe can also manage subscriptions automatically in templates.

Summary

Observables let components react to changing data over time.

Subscribe in ngOnInit and unsubscribe in ngOnDestroy to manage lifecycle.

Use Observables for timers, user events, and server data streams.