Câu hỏi phỏng vấn Angular
Câu hỏi

What is an Observable ?

Câu trả lời

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].

Characteristics of Observables

  • Lazy Execution: Observables are lazy by nature, meaning they do not start emitting values until a subscriber actively subscribes to them[1].
  • Push-based: Observables push values to the subscribers as they become available, which is different from pull-based systems where the consumer requests data[1].
  • Multiple Values: Unlike Promises, which resolve a single value, Observables can emit multiple values over time, making them suitable for handling streams of data such as user input, HTTP requests, and other continuous data sources[1][4].

Usage in Angular

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].

Subscription and Unsubscription

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].

Example

Here’s a basic example of creating and subscribing to an Observable in Angular using RxJS:

javascript Copy
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

junior

Gợi ý câu hỏi phỏng vấn

senior

What is Reactive Programming and how does it relate to Angular?

middle

Explain the difference between Promise and Observable in Angular?

expert

Explain improvements in Tree-Shaking in Angular 9

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào