0
0
Angularframework~5 mins

Why operators transform data streams in Angular

Choose your learning style9 modes available
Introduction

Operators change data as it flows through streams to make it easier to use or understand.

You want to change the format of data coming from a server before showing it.
You need to filter out unwanted data from a stream.
You want to combine multiple streams into one.
You want to delay or repeat data events.
You want to handle errors in a data stream smoothly.
Syntax
Angular
observable.pipe(operator1(), operator2(), ...)
Use pipe() to chain multiple operators in order.
Operators do not change the original data but create a new transformed stream.
Examples
This doubles each number coming from the data stream.
Angular
this.data$.pipe(map(x => x * 2))
This only lets numbers greater than 10 pass through.
Angular
this.data$.pipe(filter(x => x > 10))
This takes only the first 3 values from the stream.
Angular
this.data$.pipe(take(3))
Sample Program

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.

Angular
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));
  }
}
OutputSuccess
Important Notes

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.

Summary

Operators change data inside streams to fit your needs.

Use pipe() to combine operators in Angular.

Common operators include map, filter, and take.