angular - How to access value outside the .subscribe in angular 2 polling service
问题描述
// I was trying to get the values from outside the subscribe but it cannot assign to any variable. In my project, get the json content using http.post() method and assigned it to a variable. I want to access these variable value outside the constructor ..How can I make it possible ?
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
}
// I want to access this.result outside the subscribe and assigned to a public variable
解决方案
您正在调用getSubscription()
内部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
}
推荐阅读
- c++ - 如何将输入输入到元素数量未知的数组?(我不想使用 std::vector )
- android - Theme.MaterialComponents.DayNight 在 Firebase UI 上无法正常工作
- python - Scrapy Pagination 最多可跟踪 2 页,但必须跟踪更多
- c - 多源文件的多定义
- reactjs - 尝试从客户端连接时出现 WebSocket 问题
- javascript - 用玩笑模拟特定 url 上的 axios 请求
- javascript - 如何在我的代码中避免 Array-callback-return 错误
- flutter - 当单击 ListView 中的项目到 DetailsPage 时,如何加载不同的项目类?
- javascript - 仅使用 js 在移动设备上获取最精确位置的最佳方法
- mysql - 如何查找一整周从晚上 8 点到早上 6 点的数据