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

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

问题描述

我有一个服务,它返回一个 observable,它向我的服务器发出 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 和 observable.<小时>您不应该做的事情:

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 的发布,我们被引入了 typescript 和 observables,所以这个答案有望涵盖使用 observables 处理异步请求的基础知识.

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.

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

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