In angular we can use observables, it provide a way to work with different kinds of data. Observable can emit a single value or sequence of values, provided in bolt synchronously or asynchronously, lazily or early to a single consumer or multiple consumers.
What Are Observables?
An observable represents a sequence of values that can be observed. Observables can represent various data sources such as HTTP requests, user inputs, and even elements in the DOM.
An Observable is a function that can return a stream of values to an Observer over time, either synchronously or asynchronously. The data values returned can go from zero to an infinite range of values.
Creating Observables
In Angular, you can create Observables in several ways. The most common methods are:
Observable.create(): by using this method we can create a custom Observable by specifying the observer object.
import { Observable } from 'rxjs';
const custom = new Observable(observer => {
observer.next('Hello');
observer.next('World');
observer.complete();
});
- Built-in Operators: RxJS provides multiple built-in operators for creating it from various sources. For example, you can use these operators of rxjs like
from,of,interval, andajaxto create Observables from arrays, values, timers, or HTTP requests.
Subscribing to Observables
The First process is to create an Observable. We need to subscribe to it to get the emitted Data. Subscribing is what triggers the execution of the Observable. Here you can see how to subscribe to an Observable:
import { Observable } from 'rxjs';
const simpleObj = new Observable(observer => {
observer.next('This');
observer.next('is me');
});
const subscription = simple.subscribe(
value => console.log(value),
error => console.error(error),
() => console.log('Completed')
);
// Always unsubscribe to avoid memory leaks
subscription.unsubscribe();
In the code above:
subscribe()is called on thesimpleObservableinstance.- It will go to three callback functions as arguments:
- To emit the value it will call the first function.
- To detect errors, the second function is called
- The Observable calls the third function when it completes.
- Always unsubscribing when you’re done with the Observable is crucial to prevent memory leaks. You can do this by calling
unsubscribe()on the subscription object.
Handling Subscriptions
In Angular, we are subscribing to it by using a lifecycle hook. usually, we subscribe to Observables in the ngOnInit method of a component and unsubscribe in the ngOnDestroy method. And ensure that subscribe to it when the component is active and prevent memory leakage.
Here’s an example of subscribing to an HTTP request Observable in an Angular component:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-subscriptions-component',
template: '<div>Subscriptions Component</div>',
})
export class SubscriptionsComponent implements OnInit, OnDestroy {
private dataForSubscription: Subscription;
constructor(private httpclient: HttpClient) {}
ngOnInit() {
this.dataForSubscription = this.httpclient.get('https://api.example.com/data').subscribe(
(data) => {
// use the data
},
(error) => {
console.log(error)
}
);
}
ngOnDestroy() {
this.dataForSubscription.unsubscribe();
}
}
Using the async Pipe
we can also handle Observable using async Pipe. The async pipe automatically handles subscribing and unsubscribing and makes our code cleaner and safer. we can use the async pipe in our template file, by binding the Observable to a variable in our HTML.
<div>{{ AllData$ | async }}</div>
In your component:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-my-http-component',
template: '<div>{{ data$ | async }}</div>',
})
export class MyHttpComponent {
data$ = this.httpclient.get(//endpoint);
constructor(private httpclient: HttpClient) {}
}
Conclusion
Observables are a crucial part of Angular development, allowing you to handle asynchronous operations efficiently. Always remember to subscribe and unsubscribe from Observables to prevent memory leaks. Wheater you can subscribe to get data and unsubscribe when it is completed. you can visit the official website of rxjs to learn more about it.
For more such posts, please follow our LinkedIn page- FrontEnd Competency.