我想从我的属性 countOnProgress 中获取一个值。当我订阅时,我可以获得 countOnProgress 的值,但在订阅之外 countOnProgress 返回 0,所以我不能在 progressLastYear 中使用 countOnProgress。如何使用订阅的值设置 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)
}
}
}
谢谢
最佳答案
像下面这样重构你的代码:
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
})
});
}
为什么我的代码不起作用?
JS is Asynchronous hence it doesn't wait for any I/O request to get complete and keeps executing next lines of code.
在您的代码中,Observable.timer(0, 30000)
和 this.dashboardService.getCountProgress()
都是异步的。因此在执行 JS 时,不会等它们执行完,继续执行下一行代码。结果,方法调用 this.progressLastYear()
在服务调用完成之前被调用。因此,您没有获得 countOnProgress
的值。
关于angular - 如何在 Angular 7 中使用 typescript 获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55414219/