Subscribing to Observable
Subscribing to an Observable involves creating a subscription that listens for emissions from the Observable and executes the provided callback functions.
Syntax
observable.subscribe(
nextValueCallback,
errorCallback,
completeCallback
);
Features of Subscribing to Observable
- Provides core control over asynchronous data handling and side effects.
- Allows for error handling and completion logic.
- Enables the execution of additional code upon emission of values.
- Manual subscription management, requiring explicit unsubscription to prevent memory leaks.
- Suitable for scenarios where complex data manipulation or side effects are required.
Example
// app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, interval, Subscription } from 'rxjs';
@Component({
standalone: true,
imports: [],
selector: 'app-example',
template: '<p>Current Value: {{ currentValue }}</p>'
})
export class AppComponent implements OnInit, OnDestroy {
currentValue: number = 0;
subscription!: Subscription;
ngOnInit() {
const value$: Observable<number> = interval(1000).pipe(take(10));
this.subscription = value$.subscribe(
(value) => this.currentValue = value,
(error) => console.error(error),
() => console.log('Observable completed')
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Output:
Difference between Async Operator and Subscribing to Observable
In Angular, asynchronous programming plays a crucial role in handling data streams and managing side effects. Two common approaches for handling asynchronous data with observables are using the async operator in templates and subscribing to observables in component classes. In this article, we’ll see more about the differences between these two approaches, exploring their syntax, features, and use cases.
Table of Content
- Async Operator
- Subscribing to Observable
- Difference between async operator and subscribing to observable
- Conclusion