Vladlen Gladis
Vladlen Gladis

Reputation: 1787

How to init elements after data is loaded?

I have a service class that loads data in few methods via http. Example:

filesPerWeek(login: string): Observable<FilesLastActivity[]> {
    return this.http.get('api/report/user_files_by_week?userId=' +  login)
        .map((res: Response) => res.json());
}

In componenent.ts I get this data in ngOnInit lifecycle hook.

this.dashboardService.filesPerWeek(this.currentAccount.login).subscribe(data => {
        data.forEach(el => {
          this.barChartLabels.push(new Date(el.week).toDateString());
          this.barChartData[0].data.push(el.files);

        })

Init data in view:

<canvas
        baseChart class="chart"
        [datasets]="barChartData"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [legend]="barChartLegend"
        [chartType]="barChartType"
        [colors]="barChartColors"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)"></canvas>

Chart's wont initialize with data (screen1), only after window resize data comes in charts screen2). How to fix it?

screen1 screen1

screen2 screen2

Thanks

Upvotes: 1

Views: 816

Answers (1)

Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

In your component.ts declare a flag

private isDataAvailable:boolean=false;

And in the template in your subscribe method make this flag true when the data arrives

this.dashboardService.filesPerWeek(this.currentAccount.login).subscribe(data => {
    data.forEach(el => {
      this.barChartLabels.push(new Date(el.week).toDateString());
      this.barChartData[0].data.push(el.files);
      this.isDataAvailable=true;

    })

and in your template use ngIf

    <div *ngIf="isDataAvailable">
    <canvas
    baseChart class="chart"
    [datasets]="barChartData"
    [labels]="barChartLabels"
    [options]="barChartOptions"
    [legend]="barChartLegend"
    [chartType]="barChartType"
    [colors]="barChartColors"
    (chartHover)="chartHovered($event)"
    (chartClick)="chartClicked($event)"></canvas>

   </div>

This should probably work.You can also use async pipe for the same

Upvotes: 1

Related Questions