如何从Angle的Observable/http/async调用返回响应? [英] How do I return the response from an Observable/http/async call in angular?

查看:118
本文介绍了如何从Angle的Observable/http/async调用返回响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,该服务返回一个观察到的内容,该观察到的内容对我的服务器发出http请求并获取数据.我想使用此数据,但是我总是总是得到undefined.有什么问题吗?

I have service which returns an observable which does an http request to my server and gets the data. I want to use this data but I always end up getting undefined. What's the problem?

服务:

@Injectable()
export class EventService {

  constructor(private http: Http) { }

  getEventList(): Observable<any>{
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get("http://localhost:9999/events/get", options)
                .map((res)=> res.json())
                .catch((err)=> err)
  }
}

组件:

@Component({...})
export class EventComponent {

  myEvents: any;

  constructor( private es: EventService ) { }

  ngOnInit(){
    this.es.getEventList()
        .subscribe((response)=>{
            this.myEvents = response;
        });

    console.log(this.myEvents); //This prints undefined!
  }
}

我检查了如何返回来自一个异步调用?发布但找不到解决方案

I checked How do I return the response from an asynchronous call? post but couldn't find a solution

推荐答案

原因:

undefined的原因是您正在执行异步操作.这意味着需要花费一些时间来完成getEventList方法(主要取决于您的网络速度).

The reason that it's undefined is that you are making an asynchronous operation. Meaning it'll take some time to complete the getEventList method (depending mostly on your network speed).

所以让我们看一下http呼叫.

So lets look at the http call.

this.es.getEventList()

使用subscribe实际发出(触发")http请求后,您将等待进行响应.等待期间,javascript将执行此代码下面的行,如果遇到同步分配/操作,它将立即执行它们.

After you actually make ("fire") your http request with subscribe you will be waiting for the response. While waiting, javascript will execute the lines below this code and if it encounters synchronous assignments/operations it'll execute them immediately.

因此,在订阅getEventList()并等待响应后,

So after subscribing to the getEventList() and waiting for the response,

console.log(this.myEvents);

行将立即执行.并且它的值是undefined,直到响应从服务器到达(或首先初始化它的任何内容)之前.

line will be executed immediately. And the value of it is undefined before the response arrives from the server (or to whatever that you have initialized it in the first place).

这类似于:

ngOnInit(){
    setTimeout(()=>{
        this.myEvents = response;
    }, 5000);

    console.log(this.myEvents); //This prints undefined!
}


解决方案:

那么我们如何克服这个问题呢?我们将使用subscribe方法的回调函数.因为当数据从服务器到达时,它将与响应一起放在subscribe内部.

So how do we overcome this problem? We will use the callback function which is the subscribe method. Because when the data arrives from the server it'll be inside the subscribe with the response.

因此将代码更改为:

this.es.getEventList()
    .subscribe((response)=>{
        this.myEvents = response;
        console.log(this.myEvents); //<-- not undefined anymore
    });

将在一段时间后打印响应.


您应该做什么:

will print the response.. after some time.


What you should do:

除了记录日志之外,您的响应可能还有很多事情要做;当数据到达时,您应该在回调内部(在subscribe函数内部)执行所有这些操作.

There might be lots of things to do with your response other than just logging it; you should do all these operations inside the callback (inside the subscribe function), when the data arrives.

要提及的另一件事是,如果您来自Promise背景,则then回调对应于带有可观察对象的subscribe.


您不应该做的事情:

Another thing to mention is that if you come from a Promise background, the then callback corresponds to subscribe with observables.


What you shouldn't do:

您不应尝试将异步操作更改为同步操作(并非可以).我们进行异步操作的原因之一是,在该时间段内用户可以执行其他操作时,不要让用户等待操作完成.假设您的一个异步操作需要3分钟才能完成,如果我们没有异步操作,该界面将冻结3分钟.

You shouldn't try to change an async operation to a sync operation (not that you can). One of the reasons that we have async operations is to not make the user wait for an operation to complete while they can do other things in that time period. Suppose that one of your async operations takes 3 minutes to complete, if we didn't have the async operations the interface would froze for 3 minutes.

建议阅读内容:

此答案的原始功劳归于:如何从异步调用返回响应?

The original credit to this answer goes to: How do I return the response from an asynchronous call?

但是在angular2版本中,我们被引入了打字稿和可观察对象,因此该答案有望涵盖处理可观察对象的异步请求的基础.

But with the angular2 release we were introduced to typescript and observables so this answer hopefully covers the basics of handling an asynchronous request with observables.

这篇关于如何从Angle的Observable/http/async调用返回响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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