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

