Subscribe() method
The subscribe() method is used to manually subscribe to an Observable or Subject and receive data emitted by it.
Syntax:
observable.subscribe(
next?: (value: T) => void,
error?: (error: any) => void,
complete?: () => void
);
Features of Subscribe()
- Manual Subscription: You have control over when to start and stop listening to the data stream.
- Error Handling: You can provide an error handler function to handle any errors emitted by the Observable.
- Complete Callback: You can specify a callback function to be executed when the Observable completes.
- Ability to Perform Side Effects: You can perform additional actions or side effects based on the emitted values.
- Custom Unsubscription: You can manually unsubscribe from the Observable to prevent memory leaks.
Example
//App.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subscription, interval, of } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor(private router: Router) { }
subscription!: Subscription;
ngOnInit(): void {
const observable$ = interval(1000);
this.subscription = observable$.subscribe(
(value) => {
console.log(value);
},
(error) => {
console.error(error);
},
() => {
console.log('Observable completed');
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Output
In the above example, we have created an observable which emits a value for every second. And we have subscribed to the subscription and did a console log, to observe the values emitted by the observable created, And we have also unsubscribed to the subscription on ngOnDestroy() to avoid any memory leakage.
Difference Between subscribe() and async pipe.
In Angular, handling asynchronous data streams is an important task, and two primary methods for this are subscribe() and async pipe. Both approaches have their strengths and use cases. In this article, we will explore each method to help you understand when and how to use them effectively in your Angular applications.