What is an Observable ?
What is an Observable ?
An Observable in Angular and RxJS is a foundational concept used extensively in reactive programming to handle asynchronous operations and data streams. It is a core primitive representing a lazy, push-based collection that can emit multiple values over time, allowing developers to handle asynchronous operations more effectively[1].
In Angular, Observables are used to manage asynchronous tasks such as handling user interactions, HTTP requests, and real-time updates. Angular's HTTP module, for example, returns Observables from HTTP method calls, allowing developers to subscribe to these Observables to handle asynchronous HTTP responses[1][19].
To receive values from an Observable, a subscriber must subscribe to it. The subscription remains active until the subscriber decides to unsubscribe, which is crucial for preventing memory leaks, especially in long-lived subscriptions[1].
Here’s a basic example of creating and subscribing to an Observable in Angular using RxJS:
import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
observer.next('First value');
observer.next('Second value');
setTimeout(() => {
observer.next('Value after delay');
observer.complete();
}, 2000);
});
myObservable.subscribe({
next: data => console.log('Data:', data),
error: err => console.log('Error:', err),
complete: () => cons...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào