当前位置:网站首页>NgRx 里 first 和 take(1) 操作符的区别
NgRx 里 first 和 take(1) 操作符的区别
2022-07-31 23:16:00 【华为云】
first() 运算符采用可选的 predicate 函数,并在源完成后没有匹配的值时发出错误通知。
下列代码会报错:
import { EMPTY, range } from 'rxjs';import { first, take } from 'rxjs/operators';EMPTY.pipe(first()).subscribe(console.log, err => console.log('Jerry Error:', err));
同理,下面代码也会报错:
range(1, 5).pipe( first(val => val > 6),).subscribe(console.log, err => console.log('Error', err));
下列代码输出1:
import { EMPTY, range } from 'rxjs';import { first, take } from 'rxjs/operators';range(1, 5) .pipe(first()) .subscribe(console.log, err => console.log('Error', err));
另一方面, take(1) 只取第一个值并完成。不涉及进一步的逻辑。
import { EMPTY, range } from 'rxjs';import { first, take } from 'rxjs/operators';EMPTY.pipe( take(1),).subscribe(console.log, err => console.log('Error', err));上面代码不会有任何输出:

使用 first 操作符需谨慎,当满足下列条件使,可以使用 first:
(1)您将发出的零项视为错误条件(例如,在发出之前完成)并且如果出现错误的可能性大于 0%,则您可以优雅地处理它
(2)或者你 100% 知道源 observable 会发出至少1个项目
边栏推荐
猜你喜欢

登录业务实现(单点登录+微信扫码+短信服务)

21. Support Vector Machine - Introduction to Kernel Functions
Mysql environment installation under Linux (centos)

【Acwing】第62场周赛 题解

Unity-通过预制件和克隆方法动态实现各个UGUI下控件的创建和显示

逐步手撕轮播图3(保姆级教程)

手写一个简单的web服务器(B/S架构)
I don't know what to do with sync issues

UOS统信系统 - WindTerm使用

消息队列消息存储设计(架构实战营 模块八作业)
随机推荐
(26) About menu of the top menu of Blender source code analysis
基于单片机GSM的防火防盗系统的设计
Shell常用脚本:Nexus批量上传本地仓库脚本
登录业务实现(单点登录+微信扫码+短信服务)
SQL injection Less42 (POST type stack injection)
Audio alignment using cross-correlation
博弈论(Depu)与孙子兵法(42/100)
二叉树非递归遍历
lua入门案例实战1234定义函数与标准函数库功能
Bionic caterpillar robot source code
不知道该怎么办的同步问题
JS basic exercises
Flutter教程之 02 Flutter 桌面程序开发入门教程运行hello world (教程含源码)
Unity - LineRenderer show a line
Input and output optimization
How to debug TestCafe
Binary tree non-recursive traversal
TypeScript 的组件
EntityFramework保存到SQLServer 小数精度丢失
Fixed-length usage of nanopb string type based on RT1052 Aworks (27)