distinct 操做符能夠用來去重,將上游重複的數據過濾掉。 app
import { of } from 'rxjs'; import { distinct} from 'rxjs/operators'; // 使用of操做符產生一些數據,去重,而後訂閱 of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe( distinct() ).subscribe(x => console.log(x))
// 結果: // 1, 2, 3, 4
distinct 操做符還能夠接收一個 keySelector 的函數做爲參數:函數
import { of } from 'rxjs'; import { distinct} from 'rxjs/operators'; // 使用of操做符產生一些數據,根據name關鍵字去重,而後訂閱 of( { age: 1, name: '張三' }, { age: 2, name: '李四' }, { age: 3, name: '張三' }, ).pipe( distinct((item) => item.name), ).subscribe(x => console.log(x))
// 結果: // { age: 1, name: '張三' }, // { age: 2, name: '李四' },