Angular 6: chartjs 值未随动态值更新而更新

Angular 6: chartjs value not updating with dynamic value update

我正在使用 Angular 6

在我的 component.ts 文件中,我必须初始化图表并在 ngOnIt() 方法中这样做 ngOnIt() =15=]

@Component({
  selector: 'app-contact-detail',
  templateUrl: './contact-detail.component.html',
  styleUrls: ['./contact-detail.component.css']
})
export class ContactDetailComponent implements OnInit {

  contact_id: string;
  public graph_data_year;

  constructor(
    private activatedRoute: ActivatedRoute,
    private graphDataService: GraphDataService
  ) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe(
      param => {
        this.contact_id = param['id'];
      }
    );


    /**
     * Get Amount Given Graph Data
     */
    this.graphDataService.get_data(this.contact_id).subscribe(
      res => {
        const data = [];
        res.forEach(e => {
          data.push(e.total);
        });
        this.graph_data_year = data;
        this._setGraphData();
      }
    );

    this.initializeGraph();
  }

  _setGraphData() {
    this.lineBigDashboardChartData[0]['data'] = this.graph_data_year;

    // this console here gives updated value in the console window, but no update on chart
    console.log(this.lineBigDashboardChartData);
  }

  /**
   * Graph
   */
  initializeGraph() {
    ...

    this.lineBigDashboardChartData = [
      {
        label: 'Data',
        ...
        ...
        data: this.graph_data_year
      }
    ];
    this.lineBigDashboardChartLabels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];

    this.lineBigDashboardChartType = 'line';
  }

}

component.html就像

<canvas baseChart id="bigDashboardChart"
   [datasets]="lineBigDashboardChartData"
   [labels]="lineBigDashboardChartLabels"
   [chartType]="lineBigDashboardChartType"></canvas>

但它不会使用 graph_data_year 的更新值更新图表,该值由 this.graphDataService[=32= 更新].并显示空白图表。

console.log(this.lineBigDashboardChartData); 更新数据后在控制台打印更新值 window 但图表数据未更新。

我怎样才能在组件内部有一个异步变量,在更新时,它会在组件中使用过的每个地方更新值?或者如何在更新数据后刷新购物车?

如果将 this.initializeGraph() 移动到 ngOnInit

中的 console.log 语句下方会发生什么
this.graphDataService.get_data(this.contact_id).subscribe(
  res => {
    const data = [];
    res.forEach(e => {
      data.push(e.total);
    });
    this.graph_data_year = data;
    console.log(this.graph_data_year);
    this.initializeGraph();
  }
);

Canvas 在数据初始化之前首先加载图表。 将 *ngIf(数据有值)添加到父 div。

这可确保在加载图表之前更新数据。

请尝试像这样添加 ChartType ; [chartType]="'line'" 并且您不应该更改标签原始数组引用。 试试这个来创建动态标签;

this.lineBigDashboardChartLabels.length = 0;
this.lineBigDashboardChartLabels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];

扩展@Mehmet 的回答,这解决了我的问题。

this.lineBigDashboardChartLabels.length = 0;
this.lineBigDashboardChartLabels.push(...label_data);