RxJS:使用订阅[Working with Subscription]

创建可观察对象后,要执行可观察对象,我们需要订阅它。

count()运算符

这里是一个简单的示例,说明如何订阅可观察对象。

例子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));

输出

The count is 6

订阅有一种称为unsubscribe()的方法。调用unsubscribe()方法将删除该可观察对象使用的所有资源,即该可观察对象将被取消。这是一个使用unsubscribe()方法的工作示例。

例子2

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());
let test = final_val.subscribe(x => console.log("The count is "+x));
test.unsubscribe();

订阅存储在变量test中。我们已经使用了test.unsubscribe()。

输出

The count is 6

作者:terry,如若转载,请注明出处:https://www.web176.com/rxjs/1772.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年2月8日 上午11:33
下一篇 2021年2月8日 上午11:51

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注