// 我试图从订阅外部获取值,但它无法分配给任何变量。在我的项目中,使用 http.post() 方法获取 json 内容并将其分配给变量。我想在构造函数之外访问这些变量值..我怎样才能做到这一点?
ngOnInit(): void {
this.getSubscription();
}
// here is my subscription function
getSubscription() {
interval(5000)
.pipe(
startWith(0),
switchMap(() => this._subscriptionService.getSubData()))
.subscribe(data => {
this.Result = data; // able to print the data
JSON.stringify(this.Result);
console.log(this.Result); // able to print the data
});
console.log(this.Result); // undefined is printing
}
// 我想在订阅之外访问 this.result 并分配给公共变量
您正在呼叫getSubscription()
within ngOnInit
在执行时你的变量Result
没有设置,因为你的http请求是异步的。第一次执行订阅方法后,变量被设置。
如果其他函数需要该值,我建议您从订阅中调用它们,因为否则您无法确定您的 http 请求何时完成。
getSubscription() {
interval(5000)
.pipe(
startWith(0),
switchMap(() => this._subscriptionService.getSubData()))
.subscribe(data => {
this.Result = data; // able to print the data
JSON.stringify(this.Result);
console.log(this.Result); // able to print the data
// Is called every time you get a new result and this.Result is set now
this.processResults();
});
// Not set yet
console.log(this.Result); // undefined is printing
}
processResults() {
// Do some stuff with your results, this.Result is set now
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)