Observable Pipe In Angular

Observable Pipe In Angular

Multiple operators are chained together using the pipe method of the Angular Observable. We can use the pipe as a standalone method or as an instance method, allowing us to reuse it in numerous places. In this article, we will learn about the Observable pipe and see how to use it in an Angular application. We'll go over some pipe examples that use the map, filter, and tap operators.

RxJs Operators

The operators are crucial to the Rxjs library's functionality. They are functions that accept an observable as input and return a new observable. We employ them to manipulate the stream of observable data.

As an example.

The Map operator takes each value emitted by the source Observable and applies a supplied project function to it, then emits the results as an Observable.

The filter operator returns the filtered value as a new observable after filtering items from the source observable based on some criterion.

The table below lists some of the most regularly used operators.

AREAOPERATORS
CombinationcombineLatest, concat, merge, startWith , withLatestFrom, zip
FilteringdebounceTime,
distinctUntilChanged, filter,
take, takeUntil, takeWhile, takeLast, first, last, single, skip, skipUntil, skipWhile, skipLast,
TransformationbufferTime, concatMap, map, mergeMap, scan, switchMap, ExhaustMap, reduce
Utilitytap, delay, delaywhen
Error Handlingthrowerror, catcherror, retry, retrywhen
Multicastingshare

Using pipe to combine operators

As parameters, the pipe method supports operators like filter and map. A comma must be used to separate each argument. When a user subscribes to an observable, the pipe executes the operators in the order in which they are added, hence the order of the operators is critical.

We can use the pipe in two different ways. One technique is to use it as an observable instance, and the other is to use it as a standalone method.

We need to import observable from the rxjs library in order to use it. If you want to use the pipe standalone function, you'll have to import it as well. The rxjs/operators library contains all of the operators.

import { Observable, of, pipe} from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'

Pipe as an instance method

The pipe is used as an instance method in the following example. The operators op1, op2, and so on are supplied to the pipe method as arguments. The op1 method's output becomes the op2 operator's input, and so on.

obs.pipe(
  op1(),
  op2(),
  op3(),
  op3(),
)

Example: Pipe with Map, Filter & Tap

Here's an example of how to use the pipe operator with the map and filter operators.

import { Component, OnInit } from '@angular/core';
import { Observable, of} from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  obs = new Observable((observer) => {
    observer.next(1)
    observer.next(2)
    observer.next(3)
    observer.next(4)
    observer.next(5)
    observer.complete()
  }).pipe(
    filter(data => data > 2),                    //filter Operator
    map((val) => {return val as number * 2}),    //map operator
  )
 
 data = [];
 
  ngOnInit() {
    this.obs1.subscribe(
      val => {
        console.log(this.data)
      }
    )
  }
 
}
 
 
//result
[6, 8, 10]

The pipe operator is used in the following example, along with the map, filter, and tap operators. The tap operator creates a new observable that is a mirror of the original one. It's primarily used for debugging ( for example for logging the values of observable as shown below).

import { Component, OnInit } from '@angular/core';
import { Observable, of, pipe } from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  obs = new Observable((observer) => {
    observer.next(1)
    observer.next(2)
    observer.next(3)
    observer.next(4)
    observer.next(5)
    observer.complete()
  }).pipe(
    tap(data => console.log('tap '+data)),           //tap
    filter(data => data > 2),                        //filter
    tap(data => console.log('filter '+data)),        //tap
    map((val) => { return val as number * 2 }),      //map
    tap(data => console.log('final '+data)),         //tap
  )
 
 
  data = [];
 
  ngOnInit() {
 
    this.obs.subscribe(
      val => {
        this.data.push(val)
        console.log(this.data)
      }
    )
 
  }
}

Pipe as stand-alone method

The pipe can also be used as a standalone function to compose operators and reused in other locations.

Example

import { Component, OnInit } from '@angular/core';
import { Observable, of, pipe } from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
 
  customOperator = pipe(
    tap(data => console.log('tap '+data)),
    filter(data => data > 2),
    tap(data => console.log('filter '+data)),
    map((val) => {
      return val as number * 2
    }),
    tap(data => console.log('final '+data)),
  );
 
 
  obs = new Observable((observer) => {
    observer.next(1)
    observer.next(2)
    observer.next(3)
    observer.next(4)
    observer.next(5)
    observer.complete()
  }).pipe(    
    this.customOperator,
    tap(data => console.log('final '+data)),
  )
 
 
  data = [];
 
  ngOnInit() {
 
    this.obs.subscribe(
      val => {
        this.data.push(val)
        console.log(this.data)
      }
    )
 
  }
}

The stand-alone pipe can also be used, as seen below.

customOperator = pipe(
  tap(data => console.log('tap '+data)),
  filter(data => data > 2),
  tap(data => console.log('filter '+data)),
  map((val) => {
    return val as number * 2
  }),
  tap(data => console.log('final '+data)),
);


obs = new Observable((observer) => {
  observer.next(1)
  observer.next(2)
  observer.next(3)
  observer.next(4)
  observer.next(5)
  observer.complete()
})

ngOnInit() {
  this.customOperator(this.obs).subscribe();
}

Conclusion

In this article, we learned about the Observable pipe and see how to use it in an Angular application.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post