我想从我的属性countonprogress中获取一个值。我可以在订阅时获得countOnProgress的值,但outside subscribe countOnProgress返回0,因此我无法在progressLastYear使用countOnProgress如何用subcribe中的值设置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是异步的,因此它不等待任何I/O请求
完成并继续执行下一行代码。
在您的代码中Observable.timer(0, 30000)this.dashboardService.getCountProgress()都是异步的。因此,在执行JS时,不会等待它们完成并继续执行下一行代码结果,方法调用this.progressLastYear()在服务调用完成之前被调用。因此,您没有得到countOnProgress的值。

10-07 17:27