typescript 订阅 Observable 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38221454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subscribe Observable value
提问by Anna
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);
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:
我想用一个特定的值初始化我的 home 变量我在 ngOnInit 上做它但是当我试图把它放到外面时它得到了未定义的值:
This is my function :
这是我的功能:
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));
}
回答by Günter Z?chbauer
That's how observables work. When the response from the server arrives, the callback passed to subscribe(...)
is called by the observable.
这就是可观察的工作方式。当来自服务器的响应到达时,subscribe(...)
observable 会调用传递给的回调。
The console.log()
outside of subscribe()
is executed before the call to the server is even made.
在console.log()
外面subscribe()
的呼叫服务器之前执行,甚至制成。
回答by Fred Fuchs
My ngOnInit() had called a process that gets data from a DB.
I expected the this.##
variables which were updated in the method to be available after the call. As was described above, the call passes to observable, which means the variables are not available in ngOnInit(). But they were all populated when the HTML page displayed.
我的 ngOnInit() 调用了一个从数据库获取数据的进程。我希望this.##
方法中更新的变量在调用后可用。如上所述,调用传递到 observable,这意味着变量在 ngOnInit() 中不可用。但是它们都是在 HTML 页面显示时填充的。
So the solution is to do all the needed work inside the method and then refer to variables which will be populated in HTML.
因此,解决方案是在方法内部完成所有需要的工作,然后引用将填充在 HTML 中的变量。
this.service.getCity(zip).subscribe(
data => {
if (data.errStatus == 0) {
console.log("data: " + data.xx.List);
this.xx.List = data.xx.List;
console.log("data2: " + this.xxList);
} else {
data.errText;
console.log(data.errText);
}
},
err => console.error(err),
() => console.log('done')
);