Angular 6:Chartjs值未通过动态值更新进行更新

时间:2018-09-02 18:10:34

标签: angular chart.js angular6 angular-chart

我正在使用Angular 6

在我的 component.ts 文件中,我必须使用 ngOnIt()这样的方法来初始化图形

@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>

但是它不会使用由 this.graphDataService 更新的 graph_data_year 的更新值来更新图表。并显示空白图表。

console.log(this.lineBigDashboardChartData);在更新数据后会在控制台窗口中打印更新的值,但图表数据不会更新。

我如何在组件内部拥有一个异步变量,该变量在更新时会在组件中使用的每个位置更新值?或者更新数据后如何刷新购物车?

4 个答案:

答案 0 :(得分:0)

如果将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();
  }
);

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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