Introduction
Operators change data as it flows through streams to make it easier to use or understand.
Operators change data as it flows through streams to make it easier to use or understand.
observable.pipe(operator1(), operator2(), ...)
pipe() to chain multiple operators in order.this.data$.pipe(map(x => x * 2))
this.data$.pipe(filter(x => x > 10))
this.data$.pipe(take(3))
This Angular component creates a stream of numbers. It filters out numbers 10 or less, then doubles the remaining numbers. The result is shown in a list.
import { Component } from '@angular/core'; import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators'; @Component({ selector: 'app-root', template: `<h1>Filtered and Doubled Numbers</h1> <ul> <li *ngFor="let num of numbers">{{ num }}</li> </ul>` }) export class AppComponent { numbers: number[] = []; constructor() { const source$ = of(5, 10, 15, 20); source$ .pipe( filter(x => x > 10), map(x => x * 2) ) .subscribe(x => this.numbers.push(x)); } }
Operators help keep your code clean by handling data changes in one place.
Remember to import operators from rxjs/operators.
Operators do not change the original stream but create a new one with changes.
Operators change data inside streams to fit your needs.
Use pipe() to combine operators in Angular.
Common operators include map, filter, and take.
pipe() method to chain multiple operators together on a stream.pipe() is the standard way to combine operators like map and filter.import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
of(1, 2, 3, 4, 5).pipe(
filter(x => x % 2 === 0),
map(x => x * 10)
).subscribe(console.log);import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
of(1, 2, 3).pipe(
map(x => x * 2),
filter(x => x > 3)
).subscribe(console.log);take(3) after filtering selects 2, 4, 6.Pass the test and this pattern moves unknown