What is pipe() function in Angular

前端 未结 5 1588
时光取名叫无心
时光取名叫无心 2020-12-12 13:10

Pipes are filters for transforming data (formats) in the template.

I came across the pipe() function as below. What does this pipe() functi

5条回答
  •  醉酒成梦
    2020-12-12 14:03

    Two very different types of Pipes Angular - Pipes and RxJS - Pipes

    Angular-Pipe

    A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-hero-birthday',
      template: `

    The hero's birthday is {{ birthday | date }}

    ` }) export class HeroBirthdayComponent { birthday = new Date(1988, 3, 15); // April 15, 1988 }

    RxJS - Pipe

    Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

    import {Observable, range} from 'rxjs';
    import {map, filter} from 'rxjs/operators';
    
    const source$: Observable = range(0, 10);
    
    source$.pipe(
        map(x => x * 2),
        filter(x => x % 3 === 0)
    ).subscribe(x => console.log(x));
    

    The output for this in the console would be the following:

    0

    6

    12

    18

    For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

    So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

提交回复
热议问题