RxJ订阅后无法从服务获得Angular 2返回数据 [英] Angular 2 return data from service is not availabe after RxJs subscribe

查看:55
本文介绍了RxJ订阅后无法从服务获得Angular 2返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的map.service中,我已经这样编码

In my map.service I have coded like this

loadAdminDataDiv (): Observable<any> {
     return this.http.get("static/data/data.json")
                      .map(this.extractData);
  }
private extractData(res) {

      if (res.status < 200 || res.status >= 300) {
        throw new Error('Bad response status: ' + res.status);
      }

      //console.log(res.json());
      this.serviceData =(res.json()) ;
      return this.serviceData || { };
  }

然后将其作为提供程序注入到组件内部并像这样订阅

Then injected inside a component as a provider and subscribed like this

getSubscribeData: any;
getAllvaluesFromFiles() {
    this._mapService.loadAdminDataDiv().subscribe(data => {
      this.getSubscribeData = data;

    },
      error => { console.log(error) },
      () => {
        console.log(this.getSubscribeData);  // prints the data 

      }
    );
  }

ngAfterContentInit() {
    this.getAllvaluesFromFiles();
    console.log(this.getSubscribeData); // prints Undefined

  }

有人可以建议我解决该问题吗?我的服务正在运行,但是我的订阅数据无法在Subscribe方法之外运行.我指出了我遇到的问题.我需要在整个组件中将此this.getSubscribeData用作全局变量.我不想使用共享服务,是否可以不使用其他服务.有效的代码会有所帮助:)

Can anyone suggest me a work around with this problem ? My service is working but My subscribed data does not work outside of the subscribe method. I pointed out where I'm having problem. I need to use this this.getSubscribeData throughout my component as a global variable. I dont want to use shared service, Is that possible without using another service. A working code will be helpful :)

我必须至少再加载7个这样的变量.实际上,我需要使用这些变量将其传递给d3对象和传单地图,并且必须在进行某些必需的交互之后.可以说,我必须使用此this.getSubscribeData加载leafletmap,因此我将在订阅中启动传单地图.但是,如果我想在方法之外使用该传单实例,该怎么办?

And I have to load at least 7 more variable like this. Actually I need to use these variables to pass to d3 objects and into leaflet map and it has to be after some required interactions. Lets say, I have to load leafletmap with this this.getSubscribeData so I will initiate the leaflet map inside the subscribe. but if I want to use this leaflet instance outside of the method what should I do?

推荐答案

在此代码中

  ngAfterContentInit() {
    this.getAllvaluesFromFiles();
    console.log(this.getSubscribeData); // prints Undefined
  }

console.log(this.getSubscribeData)实际上是之前 subscribe

subscribe()安排Http的异步调用在当前执行同步线程完成时进行.
然后您的console.log(...)被执行.
然后,当最终来自服务器的响应到达时,将执行您传递给subscribe(...)的回调.

subscribe() schedules an async call for Http to make when the current sync thread of execution is completed.
Then your console.log(...) is executed.
When then eventually the response from the server arrives, the callback you passed to subscribe(...) is executed.

为了能够在响应到达时执行一些代码,您可以使用例如

To be able to execute some code when the response arrived you can use for example

  getAllvaluesFromFiles() {
    return this._mapService.loadAdminDataDiv()
    .do(data => {
      this.getSubscribeData = data;
    })
    .do(() => {
        console.log(this.getSubscribeData);  // prints the data 
    })
    .catch(error => { 
        console.log(error);
        throw error;
    });
  }

这样返回Observable

  ngAfterContentInit() {
    this.getAllvaluesFromFiles()
    .subscribe(data => {
      console.log(this.getSubscribeData); 
    })
  }

通过这种方式,可以将调用正确地链接起来,以便在数据可用后执行console.log(...).

This way the calls are properly chained so that console.log(...) is executed after the data is available.

这篇关于RxJ订阅后无法从服务获得Angular 2返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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