Thuta Learning
Angular
AdvancedWeb Developmentintermediate

Observables Intro

Observables are asynchronous data streams that come from the RxJS library. Angular uses them for HTTP requests, events, and other async operations.

typescript
import { Observable } from 'rxjs';

// Creating an Observable
const observable = new Observable(observer => {
  observer.next('First value');
  observer.next('Second value');
  
  setTimeout(() => {
    observer.next('Third value (after 2s)');
    observer.complete();
  }, 2000);
});

// Subscribing to the Observable
const subscription = observable.subscribe({
  next: (value) => console.log('Received:', value),
  error: (err) => console.error('Error:', err),
  complete: () => console.log('Stream completed!')
});

// Unsubscribe when done
// subscription.unsubscribe();

// Real example: HTTP request
this.http.get('/api/users').subscribe({
  next: (data) => this.users = data,
  error: (err) => console.error(err),
  complete: () => console.log('Request completed')
});
You should see
(The Observable emits a data stream, which subscribers then receive)
Observables Intro | Thuta Learning