angular - 如何在 Angular 7 中使用 typescript 获取属性值

标签 angular algorithm typescript angular7

我想从我的属性 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/

相关文章:

javascript - 无法在 *ngFor 中渲染数据,但它已经在 Angular 7 的控制台中显示

typescript - 字符串类型转数字

angular - 如何通过 Angular 5 中的 `httpclient` 删除请求传递正文

java - 在图上实现传输

搜索表示与特定关键字相关的图形的算法

algorithm - 在大小为 m 和 n 的 2 个排序列表的并集中找到第 k 个最小元素,效率为 log(k)

javascript - 如何快速修复和构建 NPM 包中的错误,以便构建服务器可以使用它?

angularjs - 找不到 namespace Angular

javascript - 错误类型错误 : "this.canvas is undefined" | Problem with creating a chart with angular and chart. js

javascript - 如何以 Angular 发送附加数据和表单数据