0
0
Angularframework~5 mins

Why observables matter in Angular

Choose your learning style9 modes available
Introduction

Observables help Angular apps handle data that changes over time, like user actions or server responses, in a smooth and organized way.

When you want to listen to user input events like clicks or typing.
When you need to get data from a server and update the app when the data arrives.
When you want to react to changes in data streams, like live search results.
When you want to handle multiple asynchronous tasks without messy code.
When you want to cancel ongoing tasks if they are no longer needed.
Syntax
Angular
import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.complete();
});

observable.subscribe(value => console.log(value));
Observables come from the RxJS library, which Angular uses for reactive programming.
You create an observable and then subscribe to it to get its data.
Examples
This example creates an observable that emits numbers 1, 2, and 3, then completes.
Angular
import { of } from 'rxjs';

const numbers$ = of(1, 2, 3);
numbers$.subscribe(num => console.log(num));
This listens for click events on the page and logs 'Clicked!' each time.
Angular
import { fromEvent } from 'rxjs';

const clicks$ = fromEvent(document, 'click');
clicks$.subscribe(() => console.log('Clicked!'));
Sample Program

This Angular component shows a timer that updates every second using an observable from RxJS. It also unsubscribes when the component is destroyed to prevent memory leaks.

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

@Component({
  selector: 'app-timer',
  template: `<p>Seconds passed: {{ seconds }}</p>`
})
export class TimerComponent implements OnDestroy {
  seconds = 0;
  private subscription: Subscription;

  constructor() {
    const timer$ = interval(1000); // emits every 1 second
    this.subscription = timer$.subscribe(count => this.seconds = count + 1);
  }

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

Observables make it easy to handle data that changes over time without complicated code.

They help keep your app responsive and efficient by managing asynchronous tasks well.

Remember to unsubscribe from observables when components are destroyed to avoid memory leaks.

Summary

Observables let Angular apps react to changing data smoothly.

They are useful for user events, server data, and timers.

Using observables keeps your code clean and easy to manage.