tap() vs subscribe() 设置类属性 [英] tap() vs subscribe() to set a class property
问题描述
我对 rxjs 非常陌生,只是想知道是否可以通过管道传输流并点击它来设置类属性,或者我应该在订阅中进行设置.对我来说,无论哪种方式都有效,只是想知道是否可以按照我认为适合自己的方式进行操作,或者有什么我不知道的事情.
I am very new to rxjs and was just wondering is it ok to setup a class property by piping the stream and tapping it, or it should i do it in the subscribe. To me either way works, just wonder if it is ok to do it as I see fit to my eyes or there is something I am unaware of.
展示两种方式的打字稿代码:
Typescript code demonstrating both ways:
export class ViewComponent implements OnInit {
applicant = {};
constructor(public route: ActivatedRoute, private store: Store<any>) {}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => this.store.select(state => state.applicants.entities[params.get('id')])),
tap(applicant => this.applicant = applicant)
).subscribe();
}
}
对比
export class ViewComponent implements OnInit {
applicant = {};
constructor(public route: ActivatedRoute, private store: Store<any>) {}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => this.store.select(state => state.applicants.entities[params.get('id')]))
).subscribe(applicant => this.applicant = applicant);
}
}
推荐答案
好问题.在源代码中,tap
操作符,这个评论几乎总结了它:
Good question. In the source code for the tap
operator, this comment pretty much sums it up:
这个操作符对于调试你的 Observables 以获得正确的值很有用或执行其他副作用.
注意:这与 Observable 上的 subscribe
不同.如果 do
返回的 Observable 没有被订阅,Observer 指定的副作用将永远不会发生.do
因此只是监视现有的执行,它不会像 subscribe
那样触发执行.
This operator is useful for debugging your Observables for the correct values or performing other side effects.
Note: this is different to asubscribe
on the Observable. If the Observable returned bydo
is not subscribed, the side effects specified by the Observer will never happen.do
therefore simply spies on existing execution, it does not trigger an execution to happen likesubscribe
does.
您可以在 tap
中运行的任何副作用可能也可以放在 subscribe
块中.subscribe
表示您打算主动使用源值,因为它说当这个 observable 发出时,我想将它的值保存在 applicants
变量中".tap
操作符主要用于调试,但它 可用于运行副作用.
Any side effect you can run in a tap
can probably also be put in the subscribe
block. The subscribe
indicates your intent to actively use the source value since it's saying "when this observable emits, I want to save it's value in the applicants
variable". The tap
operator is mostly there for debugging, but it can be used to run side effects.
一般来说,使用 subscribe
块来运行副作用,使用 tap
进行调试,但要注意 tap
可以做更多,如果你需要它.
In general, favor the subscribe
block for running side effects, use tap
for debugging, but be aware that tap
can do more if you need it to.
这篇关于tap() vs subscribe() 设置类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!