订阅可观察值

编程入门 行业动态 更新时间:2024-10-13 16:23:06
本文介绍了订阅可观察值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

订阅可观察值

本文发布于:2023-11-13 02:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!