RxJS - 创建运算符 count

count() 接受带有值的 Observable,并将其转换为将提供单个值的 Observable。count 函数将谓词函数作为可选参数。该函数为布尔类型,仅当值为真时才会将值添加到输出中。

语法

以下是 Count 的语法 −

count(predicate_func? : boolean): Observable

参数

predicate_func − (可选)函数将从源可观察对象中过滤要计数的值并返回布尔值。

返回值

返回值是一个具有给定数字计数的可观察对象。

让我们看一些没有谓词和有函数的计数示例。

示例 1

以下示例没有谓词函数 −

import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
final_val.subscribe(x => console.log("The count is "+x));

输出

计数为 6

示例 2

以下示例带有谓词函数 −

import { of } from 'rxjs';
import { count } from 'rxjs/operators';
let all_nums = of(1, 6, 5, 10, 9, 20, 40);
let final_val = all_nums.pipe(count(a => a % 2 === 0));
final_val.subscribe(x => console.log("计数为 "+x));

我们在计数中使用的函数仅给出偶数的计数。

输出

计数为 4