Subscribing to observables lets your app listen for data changes or events over time. It helps you react when new data arrives.
0
0
Subscribing to observables in Angular
Introduction
When you want to get data from a server and update the screen automatically.
When you need to respond to user actions like clicks or typing.
When you want to track changes in a data stream like a timer or sensor.
When you want to handle asynchronous tasks like loading files or waiting for responses.
Syntax
Angular
observable$.subscribe({
next: value => { /* handle new value */ },
error: err => { /* handle error */ },
complete: () => { /* handle completion */ }
});The subscribe method takes an object with up to three callbacks: next, error, and complete.
You can also pass just a function to handle next values if you don't need error or completion handling.
Examples
Subscribe with only the
next callback to log each new value.Angular
myObservable.subscribe(value => {
console.log('Got value:', value);
});Subscribe with all three callbacks to handle values, errors, and completion.
Angular
myObservable.subscribe({
next: value => console.log(value),
error: err => console.error('Error:', err),
complete: () => console.log('Done')
});Sample Program
This Angular component shows seconds passed by subscribing to an observable that emits a number every second. The displayed number updates automatically.
Angular
import { Component } from '@angular/core'; import { interval } from 'rxjs'; @Component({ selector: 'app-timer', template: `<p>Seconds passed: {{seconds}}</p>` }) export class TimerComponent { seconds = 0; constructor() { const timer$ = interval(1000); // emits 0,1,2,... every second timer$.subscribe({ next: val => this.seconds = val + 1, error: err => console.error('Timer error:', err), complete: () => console.log('Timer completed') }); } }
OutputSuccess
Important Notes
Always unsubscribe from observables in Angular components to avoid memory leaks, especially for long-lived observables.
Use Angular's async pipe in templates when possible to handle subscription automatically.
Summary
Subscribing lets you react to data or events over time.
Use subscribe with callbacks for next, error, and complete.
Remember to manage subscriptions to keep your app efficient.