Angular — Observables
What are Observables?
Observables are lazy collections of multiple values over time.
import { Observable } from 'rxjs';
const observable = new Observable(subscriber => {
subscriber.next('Hello');
subscriber.next('World');
subscriber.complete();
});
observable.subscribe(value => console.log(value));
Common Operators
import { map, filter, switchMap, mergeMap } from 'rxjs/operators';
// map
this.http.get('/api/users').pipe(
map(users => users.filter(u => u.active))
);
// filter
this.searchControl.valueChanges.pipe(
filter(value => value.length > 2)
);
// switchMap
this.searchControl.valueChanges.pipe(
switchMap(value => this.http.get(`/api/search?q=${value}`))
);
BehaviorSubject
import { BehaviorSubject } from 'rxjs';
const userSubject = new BehaviorSubject<any>(null);
const user$ = userSubject.asObservable();
userSubject.next({ name: 'John' });
Async Pipe
<div *ngIf="users$ | async as users">
<div *ngFor="let user of users">
{{user.name}}
</div>
</div>
Unsubscribing
// Using takeUntil
private destroy$ = new Subject<void>();
ngOnInit() {
this.data$.pipe(takeUntil(this.destroy$)).subscribe();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
Mini Practice
- Create an observable
- Use common operators
- Use BehaviorSubject
- Subscribe with async pipe
Up Next
Continue with RxJS — reactive programming in depth.
Related Topics
Frequently Asked Questions about Observables
What is Observables in Angular?
Observables is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Observables?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Observables.
Why is Observables important in Angular?
Observables is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.