Angular 2 - 直接从 Observable 返回数据 [英] Angular 2 - Return data directly from an Observable

查看:27
本文介绍了Angular 2 - 直接从 Observable 返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题,但我能够阅读的任何文档都无法回答我的问题.

I've been banging my head against this one trying to figure it out, and no amount of documentation I've been able to read has given me an answer to my question.

我有一个服务,它直接与 API 对话并返回一个可观察的事件,在正常情况下,我会订阅该事件并对数据执行我想要的操作,但是在使用来自 Restful 服务的请求的辅助服务中,我需要能够从请求中返回值.

I have a service which is speaking directly to an API and returning an observable event which under normal circumstances I would subscribe to and do what I want with the data, however in a secondary service which utilizes the requests from the restful service, I need to be able to return values from the request.

getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                res;
            },
            err => {
                console.error(err);
            }
        );
}

returnSomething() {
    return this.getSomething();
}

在上面的快速示例中,我想知道是否有任何方法可以在 returnSomething() 中从 getSomething() 返回 res>.如果无法通过这种方式实现,那么替代方案是什么?我要补充一点,_restService 非常依赖,我真的不想开始弄乱它.

In the quick example above, I want to know if there is any way I can return res from getSomething() within returnSomething(). If it's not achievable in this way, what is the alternative? I will add that the _restService is pretty heavily relied upon and I don't really want to start messing with that.

推荐答案

由于 http 调用等是异步的,您会得到一个 Observable 而不是返回的同步值.您必须订阅它,并在那里的回调中获取数据.没有办法解决这个问题.

Since http calls and the like are async, you get an Observable instead of a synchronous value returned. You have to subscribe to it, and in the callback in there you get the data. There is no way around that.

一种选择是将您的逻辑放在 subscribe 调用中

One option would be to place your logic in the subscribe call

getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                // do something here
                res;
            },
            err => {
                console.error(err);
            }
        );
}

但我喜欢这样做的方式是添加一个回调,从外部注入逻辑(可能是一个组件,也可能是另一个服务):

But the way I like doing it is to add a callback, to inject the logic from outside (maybe a component, maybe another service):

getSomething(callback: (data) => void) {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                callback(res);
            },
            err => {
                console.error(err);
            }
        );
}

在您的组件中或其他任何地方:

And in your component or wherever:

this._yourService.getSomething((data) => {
    // do something here
    console.log(data);
});

这篇关于Angular 2 - 直接从 Observable 返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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