RxJS之过滤操作符 ( Angular环境 )


一 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);
        }
      );
  }

}

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM