当前位置:网站首页>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个项目
边栏推荐
猜你喜欢
随机推荐
Federated Learning: Multi-source Knowledge Graph Embedding in Federated Scenarios
The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
LevelSequence source code analysis
Several methods for deleting specified elements in Golang slices
Difference Between Stateless and Stateful
VOT2021比赛简介
博弈论(Depu)与孙子兵法(42/100)
How to import a Golang external package and use it?
HTC使用官方固件作为底包制作rom卡刷包教程
Interview assault 69: TCP reliable?Why is that?
Advanced Algebra _ Proof _ Any matrix is similar to an upper triangular matrix
20. Support vector machine - knowledge of mathematical principles
「APIO2010」巡逻 题解
网易云信圈组上线实时互动频道,「破冰」弱关系社交
标段参数说明
MLP神经网络,GRNN神经网络,SVM神经网络以及深度学习神经网络对比识别人体健康非健康数据
SQL注入 Less38(堆叠注入)
[NLP] What is the memory of the model!
The article you worked so hard to write may not be your original
登录业务实现(单点登录+微信扫码+短信服务)








