How to Subscribe to Observable in Angular: Simple Guide
In Angular, you subscribe to an
Observable by calling its subscribe() method. This method takes a function that runs when the Observable emits data, allowing you to react to new values or handle errors.Syntax
The basic syntax to subscribe to an Observable is:
observable.subscribe(nextFunction, errorFunction, completeFunction)
Here:
nextFunctionruns when new data arrives.errorFunctionruns if an error occurs.completeFunctionruns when the Observable finishes sending data.
typescript
observable.subscribe( value => console.log('Next:', value), error => console.error('Error:', error), () => console.log('Completed') );
Example
This example shows subscribing to an Observable that emits three numbers, then completes. It logs each number, handles errors, and logs when complete.
typescript
import { of } from 'rxjs'; const numbers$ = of(1, 2, 3); numbers$.subscribe( value => console.log('Received:', value), error => console.error('Error:', error), () => console.log('Done emitting') );
Output
Received: 1
Received: 2
Received: 3
Done emitting
Common Pitfalls
Common mistakes when subscribing to Observables include:
- Not unsubscribing from Observables that never complete, causing memory leaks.
- Ignoring error handling, which can crash your app.
- Passing incorrect arguments to
subscribe().
Always unsubscribe when the Observable is long-lived, for example in Angular components' ngOnDestroy.
typescript
/* Wrong: No unsubscribe for long-lived Observable */ const subscription = observable.subscribe(value => console.log(value)); /* Right: Unsubscribe in ngOnDestroy */ import { Component, OnDestroy } from '@angular/core'; @Component({ selector: 'app-example', template: '' }) export class ExampleComponent implements OnDestroy { subscription = observable.subscribe(value => console.log(value)); ngOnDestroy() { this.subscription.unsubscribe(); } }
Quick Reference
| Method | Description |
|---|---|
| subscribe(next) | Runs function on each emitted value |
| subscribe(next, error) | Runs functions on value and error |
| subscribe(next, error, complete) | Runs functions on value, error, and completion |
| unsubscribe() | Stops receiving values to prevent memory leaks |
Key Takeaways
Use
subscribe() to listen to Observable data emissions.Always handle errors inside
subscribe() to avoid app crashes.Unsubscribe from Observables that do not complete to prevent memory leaks.
The
subscribe() method can take up to three functions: next, error, and complete.Use Angular lifecycle hooks like
ngOnDestroy to clean up subscriptions.