当我在订阅中记录我的变量的值时,我有一个值,但是当在它之外进行操作时,我得到的是不确定的???:
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.
更多推荐
订阅可观察值
发布评论