可观察的未定义 [英] Observable Undefined

查看:48
本文介绍了可观察的未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个可观察到的值中提取值,我的订阅(组件)代码如下:

I'm trying to extract the values from an observable, my subscription (component) code is as followed:

this.checkoutService.getDisabledDate().subscribe
(dates=>{this.formattedDate=dates}, 
(error:any)=>{console.log(error)});

在日期"回调中,this.formattedDate的console.log打印正确的值.但是,尝试在订阅之外访问this.formattedDate是未定义的.

In the 'dates' callback a console.log of this.formattedDate prints the correct values. However trying to access this.formattedDate outside of the subscription is undefined.

服务代码:

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

    return this.http
        .post(this.deliveryUrl,userRequest,options)
        .map((r:Response)=>r.json())
        .catch(this.handleError);
}

我已经执行了相同的操作,使用短格式()通过queryParam传递数据,在这种情况下它没有任何区别.我似乎忽略了通过此工具提取信息的必要条件.

I've performed the same action passing data over a queryParam using short form (), and it made no difference in this case. I seem to be overlooking what is necessary to pull out the information with this one.

我已经看过两个: 使用可观察对象的Angular2 HTTP订阅显示未定义的数据服务提供的Angular 2返回数据不是RxJ订阅后可用.

I've looked at both: Angular2 HTTP using observables subscribe showing data undefined and Angular 2 return data from service is not availabe after RxJs subscribe.

我在哪儿回答了他们的问题.我想念什么?

Which I'm passed where their questions were answered. What am I missing?

推荐答案

从您的问题尚不清楚外部"在哪里,但是如果在调用后您获得Observable,那么这是预期的行为

It's unclear from your question where "outside" is, but if it's after the call where you get the Observable then this is expected behavior

someMethod() {
  this.checkoutService.getDisabledDate()
  .subscribe(
    // anything here is executed sometimes later when the response from the server arrives
    dates=>{ 
      this.formattedDate=dates;
      // code that depends on the result goes here
    }, 
    (error:any)=>{console.log(error)}
  );
  // this is executed first
}

您无法获得subscribe之外的值.您可以使用map并将结果返回给调用方进行订阅,就像在getDisabledDate中所做的一样,或者将代码移至其中一个回调中.

You can't get the value outside of subscribe. You can use map and return the result for the caller to subscribe, like done in getDisabledDate or you move the code to one of the callbacks.

这篇关于可观察的未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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