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

查看:167
本文介绍了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对话并返回可观察事件的服务,在正常情况下,我会订阅该事件并对数据做我想做的事,但是在使用从宁静服务中获取请求的辅助服务中,我需要能够从请求中返回值.

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.

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

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天全站免登陆