简体   繁体   English

我应该对 RxJs 和 Angular 中的主题使用“$”符号后缀吗?

[英]Should I use "$" sign suffix for Subjects in the RxJs and Angular?

So I have this question about $ sign suffix naming convention in the RxJs code and Angular specifically.所以我有这个关于 RxJs 代码和 Angular 中的 $ 符号后缀命名约定的问题。 In angular best practices documentation and in the overall I have found that we should use it when declaring the Observable, but haven't seen using it with Subjects.在 angular 最佳实践文档中,总的来说,我发现我们应该在声明 Observable 时使用它,但还没有看到将它与 Subjects 一起使用。 Why?为什么? I thought it should mean "asynchronous".我认为它应该意味着“异步”。 Moreover Subjects are Observables.此外,主题是可观察的。 So they are async and you have to subscribe to them.所以它们是异步的,你必须订阅它们。 For now I started using $ with Subjects too.现在我也开始将 $ 与 Subjects 一起使用。 Is any real con of this practice?这种做法有什么真正的骗局吗?

Every subject is an observable .每个subject都是observable的。

If you look at Angular docs:如果您查看 Angular 文档:

This can be useful when scanning through code and looking for observable values.这在扫描代码和寻找可观察值时很有用。 Also, if you want a property to store the most recent value from an observable, it can be convenient to use the same name with or without the “$”.此外,如果您希望一个属性存储来自可观察对象的最新值,则可以方便地使用带有或不带“$”的相同名称。

The $ sign suffix doesn't mean asynchronous, its used as a soft convention to indicate that the variable is a stream. $ 符号后缀并不意味着异步,它用作软约定来指示变量是 stream。 It is more like a naming helper to indicate types.它更像是一个命名助手来指示类型。

$ suffix is used to indicate a certain variable is an observable. $后缀用于表示某个变量是可观察的。 it helps to distinguish between normal variables and observables.它有助于区分正常变量和可观察量。 its just a practice,它只是一种练习,

refer this to see the official doc explaining $ suffix.请参阅this以查看解释$后缀的官方文档。 here 这里

On top of what Stoobish and Nipuna have said, I'd add that I like to have a $ as suffix as well to avoid ending up with a same variable name when working with an extracted value from a stream.除了 Stoobish 和 Nipuna 所说的之外,我还要补充一点,我也喜欢使用$作为后缀,以避免在处理从 stream 中提取的值时使用相同的变量名。

For example:例如:

const currentTimeSeconds = currentTimeMs.pipe(
  map(currentTimeMs => currentTimeMs * 1000)
)

In the example above you'd end up with 2 variables named currentTimeMs .在上面的示例中,您最终会得到 2 个名为currentTimeMs的变量。 Sure that'd still work, but it's more confusing than helping.当然这仍然有效,但它比帮助更令人困惑。 Sure you can rename the inner variable to something different as well.当然,您也可以将内部变量重命名为不同的名称。 But overall I find it much clearer to have the following instead但总的来说,我发现使用以下内容更清楚

const currentTimeSeconds$ = currentTimeMs$.pipe(
  map(currentTimeMs => currentTimeMs * 1000)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM