tap()vs subscription()设置类属性 [英] tap() vs subscribe() to set a class property

查看:128
本文介绍了tap()vs subscription()设置类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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();
  }
}

vs

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:

此运算符对于调试Observable的正确值很有用 或有其他副作用.
注意:这与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 a subscribe on the Observable. If the Observable returned by do 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 like subscribe does.

您可以在tap中运行的任何副作用也可以放在subscribe块中. subscribe表示您打算主动使用源值,因为它说当此可观察对象发出时,我要将其值保存在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 subscription()设置类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆