如何从内部具有 Observable 订阅的函数返回值? [英] How to return value from function which has Observable subscription inside?

查看:28
本文介绍了如何从内部具有 Observable 订阅的函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何从 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())

我在这里做错了什么?

推荐答案

更新代码以反映在 RXJS 的最新版本中对管道工作方式所做的更改.所有运算符(以我的示例为例)现在都被包装到 pipe() 运算符中.

updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.

我意识到这个问题是很久以前的事了,现在你肯定有一个合适的解决方案,但对于任何寻找这个问题的人,我建议使用 Promise 来解决它以保持异步模式.

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.pipe(
           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.pipe(take(1))
       .toPromise()   
}

接收方当然和上面一样.

The receiving side stays the same as above of course.

这篇关于如何从内部具有 Observable 订阅的函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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