Javascript 使用 rxjs5 获取 BehaviorSubject 当前值的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38784566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:50:16  来源:igfitidea点击:

Simple way to get the current value of a BehaviorSubject with rxjs5

javascriptreactive-programmingrxjsrxjs5behaviorsubject

提问by Clement

Previously in rxjs4there was a method in the BehaviorSubject called: getValue()(doc here).

以前在rxjs4有一个在BehaviorSubject的方法叫: getValue()DOC这里)。

This method does not exist any more in rxjs5.

rxjs5中不再存在此方法。

So the only solution that I found to get the value of a BehaviorSubject was:

因此,我发现获得 BehaviorSubject 值的唯一解决方案是:

let value;
myBehaviorSubject.take(1).subscribe( (e) => value = e );

This code run synchronously (I do not exactly understand why, but it does ...) and get the value. It work, but it's not as clean as it could be if getValue()was present:

这段代码同步运行(我不完全明白为什么,但它确实......)并获取值。它可以工作,但它并不像getValue()存在时那样干净:

let value = myBehaviorSubject.getValue();

Why getValue()was removed in rxjs5and what's the cleanest solution to this problem?

为什么getValue()rxjs5 中被删除了,这个问题最干净的解决方案是什么?

回答by Tyson Phalp

As was pointed out by artur grzesiakin the comments, the BehaviorSubjectinterface was cleaned up, and the getter is now just .value.

正如artur grzesiak评论中所指出的,BehaviorSubject界面已经清理干净,getter 现在只是.value.

I just wanted to add this as an answer because I almost didn't read the comments to the original question, and would have missed the correct answer.

我只是想将其添加为答案,因为我几乎没有阅读原始问题的评论,并且会错过正确的答案。

Update 2019/11/05: See Jamie Barker's comment below: If anyone is using .value they will find from version 6.5.0 that it will no longer work. It was never intended for consumer use: github.com/ReactiveX/rxjs/issues/5085

2019 年 11 月 5 日更新:见下面杰米巴克的评论: If anyone is using .value they will find from version 6.5.0 that it will no longer work. It was never intended for consumer use: github.com/ReactiveX/rxjs/issues/5085

回答by Adrian Brand

Look at the source code to a behavior subject

查看行为主题的源代码

https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts

https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts

It still has a getValue method, it has a value property that just calls getValue, it was there in RxJs5.

它仍然有一个 getValue 方法,它有一个只调用 getValue 的 value 属性,它在 RxJs5 中就有。

Here is a StackBlitz using RxJs5.

这是一个使用 RxJs5 的 StackBlitz。

https://stackblitz.com/edit/typescript-gcbif4

https://stackblitz.com/edit/typescript-gcbif4

All the comments talking about a breaking change in 6.5.0 are linking to comments about observables make with of not behavior subjects.

所有关于 6.5.0 中重大变化的评论都链接到关于可观察对象的评论,而不是行为主题。