ChartJS 在Angular中订阅后,如何使用存储在方法中的数据?[Angular 11]

vsaztqbk  于 2022-12-13  发布在  Chart.js
关注(0)|答案(2)|浏览(123)

我有下面的图表,其中我想使用的数据,我已经存储在一些方法,代码的上下文:

...
charts: any
...
constructor(
    private measureService: MeasureService,
  ) { }
...
ngOnInit() {
this.getPublished()
this.getEdits()

this.chart = new Chart('canvas', {
      type: "doughnut",
      data: {
        labels: ["Test 1", "Test 2"],
        datasets: [
          {
            data: [this.numberEditing, this.numberPublished], // <- DATA GOES HERE
            backgroundColor: ['rgba(255, 0, 0, 1)', 'rgba(13, 180, 185, 1)']
          }
        ],
      },
    })
}

我用以下方法存储了来自this.numberEditing and this.numberPublished的数据(数字):

getPublishedNumber(numberPublished) {
    this.numberPublished = numberPublished
  }

  getNumberEditing(numberEditing) {
    this.numberEditing = numberEditing
  }

在发生以下订阅后,数据即存在:

getEdits() {
    this.measureService.getEditing().subscribe(data => this.getNumberEditing(data.length))
  }

getPublished() {
    this.measureService.getPublished().subscribe(data => this.getPublishedNumber(data.length))
  }

在Stackoverflow上阅读到一些类似的东西后,我得出了将数据存储在那里以供以后使用的结论,但是
我不知道如何使用这些存储在方法中的数字,在我的图表上,这怎么会发生呢?
我正在努力弄清楚Angular 仍然,已经对它只有一个星期和耶稣。

lymgl2op

lymgl2op1#

您应该使用async - await功能进行API回应。当您从API取得回应时,就可以在图表中传递这两个数据。
你必须传递数据在甜甜圈或饼图的chartjs如下:

import { Chart } from 'chart.js';

this.chart = new Chart('canvas', {
  type: 'doughnut',
  data: {
    datasets: [
      {
        data: this.numberEditing, // Alwasy number type of List. number[]
        backgroundColor: 'rgba(255, 0, 0, 1)',
      },
      {
        data: this.numberPublished, // Alwasy number type of List. number[]
        backgroundColor: 'rgba(13, 180, 185, 1)'
      }
    ]
  },
});
hfsqlsce

hfsqlsce2#

这就是为什么我们有rxjs操作符,它可以在订阅和调用之间执行中间操作。

...
charts: any
...
constructor(
    private measureService: MeasureService,
  ) { }
...
ngOnInit() {
forkJoin([
    this.getPublished(),
    this.getEdits(),
]).subscribe(() => {
    this.chart = new Chart('canvas', {
          type: "doughnut",
          data: {
            labels: ["Test 1", "Test 2"],
             datasets: [
              {
                data: [this.numberEditing, this.numberPublished], // <- DATA GOES HERE
                backgroundColor: ['rgba(255, 0, 0, 1)', 'rgba(13, 180, 185, 1)']
              }
            ],
          },
        })
});

}

然后,可以修改这些方法以返回带有管道运算符的可观察对象,后跟tap,它可以在不修改流的情况下执行操作

getEdits() {
    return this.measureService.getEditing().pipe(
        tap(data => this.getNumberEditing(data.length))
    );
  }

getPublished() {
    return this.measureService.getPublished().pipe(
        tap(data => this.getPublishedNumber(data.length))
    );
  }

相关问题