如何同步Angular2 http get? [英] How to synchronise Angular2 http get?

查看:104
本文介绍了如何同步Angular2 http get?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解使用observable我可以在请求完成时执行一个方法,但是我怎么能等到http get完成并使用ng2 http返回响应?

I understand using observable I can execute a method when the request is completed, but how can i wait till a http get is completed and return the response using in ng2 http?

getAllUser(): Array<UserDTO> {
    this.value = new Array<UserDTO>();
    this.http.get("MY_URL")
                    .map(res => res.json())
                    .subscribe(
                        data => this.value = data,
                        err => console.log(err),
                        () => console.log("Completed")
    );

    return this.value;
} 

返回时,value将为null,因为get是异步的..

the "value" will is null when its returned because get is async..

推荐答案

您不应该尝试使http调用同步。永远不是一个好主意。

You should not try to make http calls behave synchronously. Never a good idea.

来到你的 getAllUser 实现它应该从函数返回一个observable,调用代码应该订阅而不是你在方法本身内创建订阅。

Coming to your getAllUser implementation it should return an observable from the function and the calling code should subscribe instead of you creating a subscription inside the method itself.

类似

getAllUser(): Observable<UserDTO> {
        return this.http.get("MY_URL")
                        .map(res => res.json());
} 

在你调用代码时,你应该订阅并做任何你想做的事。

In you calling code, you should subscribe and do whatever you want.

这篇关于如何同步Angular2 http get?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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