订阅可观察值 [英] Subscribe Observable value

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

问题描述

当我在订阅中记录我的变量的值时,我有一个值,但是当在它之外进行操作时,我得到的是不确定的???:

When I'm logging the value of my variable inside the subscribe i have a value but when doing it outside it i get undefined ???:

this._postService.getConf("app/conf/conf.json")
   .subscribe(res =>{
      this.home = JSON.stringify(res);
      console.log("value :" + this.home);

我想使用某个值初始化我的home变量,我正在ngOnInit上执行此操作,但是当我尝试将其获取到外部时,它会得到未定义的值:

i want to initialize my home variable with a certain value I'm doing it on ngOnInit but it get the value undefined when I'm trying to get it outside:

这是我的功能:

getConf(url) {
   return this._http.get(url).
      map(res => {return res.json()});
}

ngOnInit() {

  this._postService.getConf("app/conf/conf.json")
   .subscribe(res => {
        this.home = JSON.stringify(res);
        console.log("hahowaaaaaaaa" + this.home);
   }
  );

  this._postService.getPosts(this.home)
  .subscribe(result =>{ 
    this.loading = false;
    this.actionsG = result; 
    var count = JSON.stringify(result);

    this.aCount = count.substring(count.indexOf(','),23);

  },error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsG'));

  this._postService.getPosts(this.home ).subscribe(result => this.actionsV = 
    result, error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsV ngOnInit' + this.page));
}

推荐答案

这就是可观察对象的工作方式.当来自服务器的响应到达时,被观察者调用传递给subscribe(...)的回调.

That's how observables work. When the response from the server arrives, the callback passed to subscribe(...) is called by the observable.

subscribe()之外的console.log()是在甚至调用服务器之前执行的.

The console.log() outside of subscribe() is executed before the call to the server is even made.

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

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