[英]How to get value of property using typescript in angular 7
I want to take a value from my property, countOnProgress. 我想从我的属性countOnProgress中获取一个值。 I can get the value of countOnProgress when I subcribe, but outside subscribe countOnProgress return 0 so I cant use countOnProgress at progressLastYear.
我可以在订阅时获得countOnProgress的值,但在外部订阅countOnProgress时返回0,所以我不能在progressLastYear使用countOnProgress。 How to set value of countOnProgress with value from subcribe without return 0
如何使用来自订阅的值设置countOnProgress的值而不返回0
import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { DashboardService } from './dashboard.service';
import { Observable, of, timer } from 'rxjs';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer';
@Component({
templateUrl: 'dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
alive = true;
countOnProgress:number = 0;
max: number = 200;
value: number = 100;
stacked: any[] = [];
constructor(@Inject (DashboardService) private dashboardService: DashboardService){
}
ngOnInit(): void {
Observable.timer(0, 30000)
.takeWhile(() => this.alive)
.subscribe(() => {
this.dashboardService.getCountProgress().subscribe(resp => {
this.countOnProgress = resp.d;
console.log(this.countOnProgress); //It found the data
})
});
this.progressLastYear();
}
progressLastYear(): void{
const types = ['success', 'info', 'warning', 'danger'];
const values = [this.countOnProgress];
console.log(values);
this.stacked = [];
for (let i = 0; i < 5; i++) {
this.stacked.push({
value: values[1],
type: types[i],
label: values[1]
});
console.log(this.stacked); //The datas: 0, succes, 0 (didnt get countOnProgress' value)
}
}
}
Thank you 谢谢
Refactor your code like below : 重构您的代码,如下所示:
ngOnInit(): void {
Observable.timer(0, 30000)
.takeWhile(() => this.alive)
.subscribe(() => {
this.dashboardService.getCountProgress().subscribe(resp => {
this.countOnProgress = resp.d;
console.log(this.countOnProgress); //It found the data
this.progressLastYear(); // < -- move the function call here
})
});
}
Why My code is not working ? 为什么我的代码不起作用?
JS is Asynchronous hence it doesn't wait for any I/O request to get complete and keeps executing next lines of code.
JS是异步的,因此它不等待任何I / O请求完成,而是继续执行下一行代码。
In you code both Observable.timer(0, 30000)
and this.dashboardService.getCountProgress()
is asynchronous . 在您的代码中,
Observable.timer(0, 30000)
和this.dashboardService.getCountProgress()
都是异步的。 Hence while executing JS will not wait for them to get complete and keep executing the next line of code. 因此,在执行JS时不会等待它们完成并继续执行下一行代码。 As a result the method call
this.progressLastYear()
got called before the completion of the service call . 结果,在服务调用完成之前调用了方法
this.progressLastYear()
。 Hence You were not getting the value of countOnProgress
. 因此,您没有得到
countOnProgress
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.