Nature of Observable
Observables in Angular work on a publish-subscribe mechanism. This means that an Observable produces a data stream, and subscribers listen for changes or updates in that stream.
Key Characteristics
- Lazy Evaluation: Observables do not emit data until subscribed.
- Multiple Subscribers: One Observable can have multiple subscribers, all receiving the same data.
- Unsubscription: Subscriptions can be manually terminated to prevent memory leaks.
Example
import { Observable } from 'rxjs';
const observable = new Observable(subscriber => {
subscriber.next('First value');
subscriber.next('Second value');
subscriber.complete();
});
observable.subscribe({
next: value => console.log(value),
complete: () => console.log('Completed!')
});
Output:
First value
Second value
Completed!
Usage
Observables are used in Angular for various purposes, such as:
- HTTP Requests: Fetching data from a server using Angular’s HttpClient.
- Event Handling: Listening to events like button clicks.
- Form Value Changes: Reacting to changes in form inputs using Angular Forms.
- WebSocket Communication: Handling real-time communication.
Example of using Observables in an HTTP request:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
template: `<div *ngIf="users">{{ users | json }}</div>`
})
export class UserComponent implements OnInit {
users: any;
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('https://jsonplaceholder.typicode.com/users')
.subscribe(data => this.users = data);
}
}
Creating an Observable
You can create an Observable in Angular using the Observable constructor or helper functions from RxJS like of or from.
Example of manually creating an Observable:
import { Observable } from 'rxjs';
const customObservable = new Observable(subscriber => {
subscriber.next('Hello');
subscriber.next('World');
setTimeout(() => {
subscriber.complete();
}, 1000);
});
customObservable.subscribe({
next: value => console.log(value),
complete: () => console.log('Stream completed')
});
Output:
Hello
World
Stream completed
Making API Integration to Check Values
Integrating APIs using Observables is a common task in Angular applications. Below is an example:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-data-fetch',
template: `<ul>
<li *ngFor="let item of data">{{ item.name }}</li>
</ul>`
})
export class DataFetchComponent implements OnInit {
data: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.fetchData().subscribe(result => this.data = result);
}
fetchData(): Observable<any[]> {
return this.http.get<any[]>('https://jsonplaceholder.typicode.com/users');
}
}
Explanation:
- fetchData method returns an Observable.
- The component subscribes to the Observable to retrieve the data.
Output: A list of user names fetched from the API will be displayed.
Types of Notifications and Description
Observables in Angular can emit different types of notifications:
- Next: Emits a value in the stream.
- Error: Emits an error if something goes wrong.
- Complete: Signals that the stream has ended.
Example:
const observable = new Observable(subscriber => {
subscriber.next('Data 1');
subscriber.next('Data 2');
subscriber.error('An error occurred!');
subscriber.complete();
});
observable.subscribe({
next: value => console.log('Next:', value),
error: err => console.error('Error:', err),
complete: () => console.log('Stream completed')
});
Output:
Next: Data 1
Next: Data 2
Error: An error occurred!
Frequently Asked Questions
What is the primary purpose of Observables in Angular?
Observables are used to handle asynchronous data streams, such as HTTP requests and event listeners, allowing developers to manage data flow efficiently.
How do Observables differ from Promises?
Observables can handle multiple values over time and provide more functionality, like cancellation and multiple subscriptions, unlike Promises that resolve once.
Why is unsubscription important in Angular Observables?
Unsubscribing prevents memory leaks by terminating unused Observables.
Conclusion
In this article, we discussed the concept of Observables in Angular, their nature, usage, and how to create and work with them. Observables play a crucial role in handling asynchronous operations, making applications efficient and responsive.