为什么此错误/错误出现在角度

时间:2018-11-20 03:07:09

标签: javascript python angular typescript

我正在使用python-flask在前端和后端创建一个有角度的项目,但是,在上一次我试图使数据库出现时,控制台显示错误...但是页面正确更新。这是代码示例。

这是显示错误但仍显示正确数据的位置。

 <div class=" w3-half" layout="column">
<div id="chartContainer2"  style="margin-top:2%; height: 100%; width: 100%;">

    <h3 class="titulo">YOUR TIME BANK: {{grafico.horas_aluno}}</h3>

    <div style="display: block;">
      <canvas baseChart
                  [data]="doughnutChartData2"
                  [labels]="doughnutChartLabels2"
                  [colors]="colors2"
                  [chartType]="doughnutChartType2"
                  [legend]="doughnutchartDisplay2"
                  (chartHover)="chartHovered2($event)"
                  (chartClick)="chartClicked2($event)"></canvas>
    </div>
</div>

这是调用所引用的打字稿

import { Component, OnInit, NgModule } from '@angular/core';
import { GoogleChartsModule } from 'angular-google-charts';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-pagina',
  templateUrl: './pagina.component.html',
  styleUrls: ['./pagina.component.css']
})
@NgModule({
  declarations: [PaginaComponent],
  imports: [GoogleChartsModule.forRoot(),],
  bootstrap: [PaginaComponent],
})


export class PaginaComponent implements OnInit {


  serverData: JSON;
  employeeData: JSON;


  constructor(private http: HttpClient) { }


  alunos:any;
  grafico:JSON;
  ngOnInit() {
    this.http.get('http://127.0.0.1:5002/222222').subscribe(dados => { 
      console.log(dados)
      this.alunos = [dados as JSON];
    })

    this.http.get('http://127.0.0.1:5002/chart/222222').subscribe(dados => { 
      console.log(dados)
      this.grafico = dados as JSON;
    })

  }


  public doughnutChartLabels2:string[] = ['Total time', 'Remaining time', 'Missing time'];
  public colors2 = [{
    backgroundColor: ['rgba(17, 168, 0, 1)','rgba(189, 0, 0, 1)', 'rgba(0, 72, 240, 1)'],
    fillColor: 'rgba(47, 132, 71, 0.8)',
    strokeColor: 'rgba(47, 132, 71, 0.8)',
    highlightFill: 'rgba(47, 132, 71, 0.8)',
    highlightStroke: 'rgba(47, 132, 71, 0.8)'
}];





  public doughnutChartData2:number[] = [3,45,1];
  public doughnutchartDisplay2 = false;
  public titleChart2 = [{display:true}];
  public doughnutChartType2:string = 'doughnut';

  // events
  public chartClicked2(e:any):void {
    console.log(e);
  }

  public chartHovered2(e:any):void {
    console.log(e);
  }

}

这是控制台上显示的错误:ERROR TypeError: "_co.grafico is undefined"

1 个答案:

答案 0 :(得分:2)

尝试使用安全的导航运算符,因为数据是通过api调用异步加载的

<h3 class="titulo">YOUR TIME BANK: {{grafico?.horas_aluno}}</h3>