一 take操作符
只发出源 Observable 最初发出的的N个值 (N = count)。 如果源发出值的数量小于 count 的话,那么它的所有值都将发出。然后它便完成,无论源 Observable 是否完成。
1import { Component, OnInit } from '@angular/core'; 2import { range } from 'rxjs/observable/range'; 3import { take } from 'rxjs/operators/take'; 4 5@Component({ 6 selector: 'app-filter', 7 templateUrl: './filter.component.html', 8 styleUrls: ['./filter.component.css'] 9}) 10export class FilterComponent implements OnInit { 11 12 constructor() { } 13 14 ngOnInit() { 15 range(100, 10) 16 .pipe(take(5)) 17 .subscribe(val => { 18 console.log(val); 19 }); 20 } 21 22}

二 distinctUntilChanged操作符
返回 Observable,它只发出源 Observable 发出的与前一项不相同的项。
如果没有提供 compare 函数,默认使用===严格相等检查。
1import { Component, OnInit } from '@angular/core'; 2import { of } from 'rxjs/observable/of'; 3import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged'; 4 5@Component({ 6 selector: 'app-filter', 7 templateUrl: './filter.component.html', 8 styleUrls: ['./filter.component.css'] 9}) 10export class FilterComponent implements OnInit { 11 12 constructor() { } 13 14 ngOnInit() { 15 of(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3) 16 .pipe(distinctUntilChanged()) 17 .subscribe( 18 val => { 19 console.log(val); 20 } 21 ); 22 } 23 24}

如果提供了 compare 函数,那么每一项都会调用它来检验是否应该发出这个值。
1import { Component, OnInit } from '@angular/core'; 2import { of } from 'rxjs/observable/of'; 3import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged'; 4 5export class Person { 6 constructor(public name: string, public age: number) { } 7} 8 9@Component({ 10 selector: 'app-filter', 11 templateUrl: './filter.component.html', 12 styleUrls: ['./filter.component.css'] 13}) 14export class FilterComponent implements OnInit { 15 16 constructor() { } 17 18 ngOnInit() { 19 of<Person>( 20 new Person('Leo', 11), 21 new Person('Raph', 12), 22 new Person('Mikey', 13), 23 new Person('Mikey', 14) 24 ) 25 .pipe( 26 // of方法使用了泛型,可以省略指定p、q为Person类型 27 distinctUntilChanged((p, q) => p.name === q.name) 28 ) 29 .subscribe( 30 val => { 31 console.log(val); 32 } 33 ); 34 } 35 36}
