Observables are a key concept in Angular, and they come from the RxJS (Reactive Extensions for JavaScript) library, which is a powerful library for reactive programming. RxJS is a core dependency of Angular, and it brings in a way to efficiently handle async operations and manage data streams.
## Observables
An Observable is a data producer and can be thought of as a special kind of function that emits multiple values over time. You can think of Observables as a blueprint for creating streams and enabling functions to regularly emit data which can be passed to multiple consumers.
Observables are lazy by nature, meaning that they will not start emitting values immediately when they are created but only when they are explicitly subscribed to.
Let’s consider a simple example:
import { Observable } from 'rxjs';
const observable = new Observable((observer) => {
observer.next(1);
observer.next(2);
observer.next(3);
setTimeout(() => {
observer.next(4);
observer.complete();
}, 1000);
});
In this example, we have created a new Observable that emits four values: 1, 2, 3, and after waiting for a second, it emits 4, and then completes. To start consuming the values emitted by this Observable, we need to subscribe to it:
observable.subscribe((value) => console.log(value));
This would output 1, 2, 3, and then wait for a second and output 4.
## How Observables are used in Angular
Observables are used extensively in Angular for tasks such as handling HTTP Requests, managing user interface events, interacting with forms, and handling navigation between views.
Here are a few examples of how Observables are used in Angular:
### 1. HTTP Requests
Angular’s ‘HttpClient‘ module uses Observables to handle HTTP requests. When you make an HTTP request, it returns an Observable, and you can subscribe to it to handle the response:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {
this.http.get('https://api.example.com/data').subscribe((response) => {
console.log(response);
});
}
### 2. Event Binding in Templates
Observables are used with Angular’s event binding system to manage events. For example, you can create a custom event handler that returns an Observable to emit events when a button is clicked:
<button (click)="onClick()">Click me!</button>
import { Observable, Subject } from 'rxjs';
private clickSubject = new Subject<void>();
public onClick(): void {
this.clickSubject.next();
}
public get buttonClick$(): Observable<void> {
return this.clickSubject.asObservable();
}
### 3. Form Handling
Angular’s reactive forms module uses Observables to manage form inputs and validation. Values entered in form inputs can be subscribed to using Observables, and any changes to the form values can be tracked and processed reactively.
import { FormGroup, FormControl } from '@angular/forms';
myForm = new FormGroup({
name: new FormControl('')
});
constructor() {
this.myForm.valueChanges.subscribe((value) => {
console.log('Form value changed:', value);
});
}
### 4. Routing and Navigation
Angular’s router module also makes use of Observables for route handling and navigation. When routes change, you can subscribe to the router to get the new route parameters, query parameters, or data.
import { ActivatedRoute, Params } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.params.subscribe((params: Params) => {
console.log('Route parameters:', params);
});
}
In summary, Observables are a powerful pattern in Angular for handling asynchronous operations, managing event-driven user interfaces, and streamlining data processing. They make it easier to work with complex async operations and create clean, maintainable code.