Не удалось создать диаграмму: невозможно получить контекст из данного элемента - PullRequest
0 голосов
/ 10 сентября 2018

Мне нужно отобразить 3 простые кольцевые диаграммы в угловом проекте на одном и том же компоненте.У меня есть 3 директивы diff, чтобы создать кольцевую диаграмму и установить для нее innerHTML холста.

мой component.html равен

  <div  id="myDiv" class="details" [style.width.%]=chartWidth  >
    <canvas appEmployeeChart id="myCanvas" (click)="click('empChart')"></canvas>
  </div>

   <div  id="managerDiv" class="details" [style.width.%]=chartWidth >
    <canvas appManagerChart id="managerCanvas" (click)="click('empChart')"></canvas>
  </div>

  <div  id="hrDiv" class="details" [style.width.%]=chartWidth >
    <canvas appHrChart id="hrCanvas"></canvas>
  </div>

директива appEmployeeChart равна

chart: Chart;

  options = {
    responsive: true,
    title: {
      display: true,
      position: "top",
      text: "Leave Docklet",
      fontSize: 18,
      fontColor: "#111"
    },
    legend: {
      display: true,
      position: "bottom",
    },
    tooltips: {
      enabled: true
    },
    pieceLabel: {
      mode: 'value',
      visible: true,
      fontSize: 18,
      fontColor: "#111"
    },
    label: {visible: true}
  };


  constructor(private employeeService: EmployeeService, el: ElementRef, renderer: Renderer) {

    //let employee = JSON.parse(sessionStorage.getItem('employee'));
    let currentEmpUserDetails = JSON.parse(sessionStorage.getItem('empUserDetails'));
    const currentEmpSysRole = currentEmpUserDetails.lmsSytsemRoles;

    if (currentEmpSysRole.indexOf("GetMyLeaves") == -1) {



      this.employeeService.getLeaves('P').subscribe(lf => {
        let pendingLeaves = lf.length;

        this.employeeService.getLeaves('A').subscribe(lf => {
          let approvedLeaves = lf.length;

          this.employeeService.getLeaves('R').subscribe(lf => {
            let rejectedLeaves = lf.length;

            this.employeeService.getLeaves('C').subscribe(lf => {
              let canceledLeaves = lf.length;

              this.employeeService.getBalanceLeaves().subscribe(lf => {
                let balanceLeaves = lf;

                this.employeeService.getOptionalLeaves().subscribe(lf => {
                  let optionalLeaves = lf;

                  this.chart = new Chart('myLeavesCanvas', {
                    type: 'doughnut',
                    data: {
                      labels: ["Leaves Pending", "Leaves Approved", "Rejected Leaves", "Canceled Leaves", "Balance Leaves", "Optional Leaves"],
                      datasets: [
                        {
                          label: ['P', 'A', 'R', 'C', 'B', 'O'],
                          data: [pendingLeaves, approvedLeaves, rejectedLeaves, canceledLeaves, balanceLeaves, optionalLeaves],
                          backgroundColor: [
                            "#33CCFF",
                            "#08526B",
                            "#687073",
                            "#203ECB",
                            "#D5D7E0",
                            "#46DCBB"
                          ],
                          borderColor: [
                            "#33CCFF",
                            "#08526B",
                            "#687073",
                            "#203ECB",
                            "#D5D7E0",
                            "#46DCBB"
                          ],
                          borderWidth: [1, 1, 1, 1, 1, 1]
                        }
                      ]
                    },
                    options: this.options
                  });
                });
              });
            });
          });
        });
      });


      renderer.setElementProperty(el.nativeElement, 'innerHTML', this.chart);

appHrChartDirective is

export class HrChartDirective {

  hrChart: Chart;

  options = {
    responsive: true,
    title: {
      display: true,
      position: "top",
      text: "My Team Docklet",
      fontSize: 18,
      fontColor: "#111"
    },
    legend: {
      display: true,
      position: "bottom",
    },
    tooltips: {
      enabled: true
    },
    pieceLabel: {
      mode: 'value',
      visible: true,
      fontSize: 18,
      fontColor: "#111"
    },
    label: {visible: true}
  };


  constructor(el: ElementRef, renderer: Renderer, private managerService: ManagerService) {
    alert('hr  directive loaded');

    let pendingLeaves = 6;
    let approvedLeaves = 6;
    let rejectedLeaves = 6;
    this.hrChart = new Chart('hrLeavesCanvas', {
      type: 'doughnut',
      data: {
        labels: ["Leaves Pending", "Leaves Approved", "Rejected Leaves"],
        datasets: [
          {
            label: ['P', 'A', 'R'],
            data: [pendingLeaves, approvedLeaves, rejectedLeaves],

            backgroundColor: [
              "#FFFF00",
              "#008000",
              "#FF0000"
            ],
            borderColor: [
              "#FFFF00",
              "#008000",
              "#FF0000"
            ],
            borderWidth: [1, 1, 1]
          }
        ]
      },
      options: this.options
    });

    alert(this.hrChart.canvas);

    renderer.setElementProperty(el.nativeElement, 'innerHTML', this.hrChart);


  }

Теперь диаграмма myDiv и ManagerDiv загружается без проблем, но 3-я диаграмма, т. Е. Диаграмма hrDiv не загружена, и я получаю Не удалось создать диаграмму: не удается получить контекст из данного элемента ошибка в консоли.

Я пытаюсь отладить проблему с помощью отладчика javascript и наблюдаю, что в угловом режиме сначала пытаются загрузить 3-ю (hrDiv) диаграмму, и в это время нет элемента html, поэтому canvas с id hrCanvas не найден, и он не смог загрузить диаграмму.

в следующий раз, когда он попытается загрузить managerCanvas, элемент html присутствует и диаграмма загружена успешно.

Примечание: Единственное различие между appManagerDirective и appHrDirective заключается в том, что appManagerDirective переносит данные, потребляя остальные службы, где appHrDirective испытывает трудности.закодированные данные.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...