rxjs过滤操作符

一 take操作符

只发出源 Observable 最初发出的的N个值 (N = count)。 如果源发出值的数量小于 count 的话,那么它的所有值都将发出。然后它便完成,无论源 Observable 是否完成。

import { Component, OnInit } from '@angular/core';

import { range } from 'rxjs/observable/range';

import { take } from 'rxjs/operators/take';

@Component({

    selector: 'app-filter',

    templateUrl: './filter.component.html',

    styleUrls: ['./filter.component.css']

})

export class FilterComponent implements OnInit {

  constructor() { }

   ngOnInit() {

    range(100, 10)

    .pipe(take(5))

     .subscribe(val => {

        console.log(val);

      });

    }

}

 

二 distinctUntilChanged操作符

返回 Observable,它只发出源 Observable 发出的与前一项不相同的项。

如果没有提供 compare 函数,默认使用===严格相等检查。

import { Component, OnInit } from '@angular/core';

import { of } from 'rxjs/observable/of';

import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged';

@Component({

  selector: 'app-filter',

  templateUrl: './filter.component.html',

  styleUrls: ['./filter.component.css']

})

export class FilterComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    of(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3)

    .pipe( distinctUntilChanged() )

    .subscribe( val => {

      console.log(val);

    } );

  }

}

 

如果提供了 compare 函数,那么每一项都会调用它来检验是否应该发出这个值。

import { Component, OnInit } from '@angular/core';

import { of } from 'rxjs/observable/of';

import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged';

export class Person {

    constructor(public name: string, public age: number) { }

}

@Component({

   selector: 'app-filter',

  templateUrl: './filter.component.html',

  styleUrls: ['./filter.component.css']

})

export class FilterComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    of<Person>(

      new Person('Leo', 11),

      new Person('Raph', 12),

      new Person('Mikey', 13),

      new Person('Mikey', 14)

    ) .pipe(

      // of方法使用了泛型,可以省略指定p、q为Person类型

      distinctUntilChanged((p, q) => p.name === q.name)

    )

    .subscribe( val => {

       console.log(val);

     } );

   }

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值