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

查看:127
本文介绍了如何从angular2中的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!
  }
}


推荐答案

原因:

它是 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()

订阅实际制作(开火)您的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.

所以在订阅<$ c $之后c> 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 背景,然后回调对应于使用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.

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

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