如何从内部具有Observable订阅的函数返回值? [英] How to return value from function which has Observable subscription inside?
问题描述
我不知道如何从Observable中提取值以由存在Observable的函数返回.我只需要从中返回一个值,就别无所求.
I dont know how to extract value from Observable to be returned by function in which Observable is present. I need just a value from it to be returned, nothing else.
当前版本有效
function getValueFromObservable() {
this.store.subscribe(
(data:any) => {
console.log(data)
}
)
}
getValueFromObservable()
我需要它工作,函数才能返回值,然后:
I need this to work, function to return value, and then:
function getValueFromObservable() {
this.store.subscribe(
(data:any) => {
return data
}
)
}
console.log(getValueFromObservable())
我在做什么错了?
推荐答案
我意识到这个问题已经有一段时间了,您现在肯定已经找到了正确的解决方案,但是对于任何寻求此解决方案的人,我建议您使用保证保持异步模式.
I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.
更详细的版本将创建一个新的Promise:
A more verbose version would be creating a new Promise:
function getValueFromObservable() {
return new Promise(resolve=>{
this.store
.take(1) //useful if you need the data once and don't want to manually cancel the subscription again
.subscribe(
(data:any) => {
console.log(data);
resolve(data);
})
})
}
在接收端,您将等待"等待诺言解决,如下所示:
On the receiving end you will then have "wait" for the promise to resolve with something like this:
getValueFromObservable()
.then((data:any)=>{
//... continue with anything depending on "data" after the Promise has resolved
})
一种更苗条的解决方案是使用RxJS的.toPromise()代替:
A slimmer solution would be using RxJS' .toPromise() instead:
function getValueFromObservable() {
return this.store
.take(1)
.toPromise()
}
接收方当然与上面相同.
The receiving side stays the same as above of course.
这篇关于如何从内部具有Observable订阅的函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!