2017-01-16 8 views
0

Мой HTML разметки выглядит следующим образом, где я использую PieChart библиотеки NG2-карты, которая зависимость от chart.js:Брус присвоить данные NG2 PieChart после его получения в ответ HTTP

<h2>Home</h2> 
<div style="display: block"> 
    <canvas baseChart class="chart" 
      [data]="pieChartData" 
      [labels]="pieChartLabels" 
      [chartType]="pie" 
      (chartHover)="chartHovered($event)" 
      (chartClick)="chartClicked($event)"> 
    </canvas> 
</div> 

я написал следующее код добавить его работает отлично. Я могу видеть график и получать вызовы к обработчикам событий. Мой код компонента (рабочий) выглядит следующим образом:

import {Component, OnInit, AfterViewInit, AfterContentInit} from '@angular/core'; 
import {NgClass} from '@angular/common'; 

import {PieChartData} from '../shared/pie-chart-data'; 
import {HotelsService} from '../components/hotel/hotels.service'; 
import {Hotel} from '../entities/hotel'; 


import * as _ from 'underscore/underscore'; 

@Component({ 
    selector:'home' 
    , templateUrl:'app/home/home.component.html' 
}) 
export class HomeComponent implements OnInit{ 
    hotels: Hotel[]; 
    hotelCountByCity; 
    data = new PieChartData(); 

    pieChartData = []; 
    pieChartLabels=[]; 

    constructor(private _hotelsService: HotelsService){} 

    ngOnInit(){ 
     this.getActiveHotelsByCity();   

     console.log("On Init"); 
    } 

    // events 
    public chartClicked(e:any):void { 
     // TODO : should open another chart which is not decided. 
    } 

    public chartHovered(e:any):void { 
     // TODO : do something 
    } 

    private getActiveHotelsByCity(){ 
     //this.data.pieChartType = "pie"; 
     this.pieChartLabels = ["One", "Two", "Three"]; 
     this.pieChartData = [100,200,300]; 
    } 
} 

Но когда я пытаюсь получить данные из веб-службы и назначить его PieChart, я получаю странные ошибки. Мой код компонента (не работает):

import {Component, OnInit, AfterViewInit, AfterContentInit} from '@angular/core'; 
import {NgClass} from '@angular/common'; 

import {PieChartData} from '../shared/pie-chart-data'; 
import {HotelsService} from '../components/hotel/hotels.service'; 
import {Hotel} from '../entities/hotel'; 

import * as _ from 'underscore/underscore'; 

@Component({ 
    selector:'home' 
    , templateUrl:'app/home/home.component.html' 
}) 
export class HomeComponent implements OnInit{ 
    hotels: Hotel[]; 
    hotelCountByCity; 
    data = new PieChartData(); 

pieChartData = []; 
pieChartLabels=[]; 

constructor(private _hotelsService: HotelsService){} 

ngOnInit(){ 
    this.getActiveHotelsByCity();   

    console.log("On Init"); 
} 

// events 
public chartClicked(e:any):void { 
    // TODO : should open another chart which is not decided. 
} 



    public chartHovered(e:any):void { 
     // TODO : do something 
    } 

    private getActiveHotelsByCity(){ 
     this._hotelsService.getAllActiveHotels() 
           .subscribe(
            res => this.hotelCountByCity = 
                _.countBy(
                 res.data.hotels 
                 ,function(hotel: Hotel) { 
                  return hotel.address.city; 
                 }) 
            ,null 
            ,()=> { 
             this.pieChartLabels = _.keys(this.hotelCountByCity); 
             this.pieChartData = _.values(this.hotelCountByCity); 
             console.log("Reached success part of request"); 
            } 
           ); 
    } 
} 

Стек локон за ошибки я получаю в первый заключается в следующем:

EXCEPTION: Uncaught (in promise): TypeError: Cannot set property stack of [object Object] which has only a getter TypeError: Cannot set property stack of [object Object] which has only a getter at assignAll (http://localhost:3000/node_modules/zone.js/dist/zone.js:704:29) at ViewWrappedError.ZoneAwareError (http://localhost:3000/node_modules/zone.js/dist/zone.js:775:16) at ViewWrappedError.BaseError [as constructor] (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:1104:38) at ViewWrappedError.WrappedError [as constructor] (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:1133:20) at new ViewWrappedError (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:5106:20) at _View_HomeComponent_Host0.DebugAppView._rethrowWithContext (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9427:27) at _View_HomeComponent_Host0.DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9413:22) at ViewRef_.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:7398:24) at RouterOutlet.activate (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:3458:46) at ActivateRoutes.placeComponentIntoOutlet (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2955:20) at ActivateRoutes.activateRoutes (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2933:26) at eval (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2902:23) at Array.forEach (native) at ActivateRoutes.activateChildRoutes (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2901:33) at ActivateRoutes.activate (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2896:18)

Я понимаю, что это не реальная ошибка после того, как копаться в Интернете. Я нашел некоторые рекомендации по Интернету, чтобы найти реальную ошибку и реальную ошибку я нашел, была:

"TypeError: Chart.controllers[meta.type] is not a constructor at Chart.Controller. (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:8508:24) at Object.helpers.each (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:9345:15) at Chart.Controller.buildOrUpdateControllers (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:8497:12) at Chart.Controller.initialize (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:8356:7) at new Chart.Controller (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:8339:6) at new Chart (http://localhost:3000/node_modules/chart.js/dist/Chart.bundle.js:10684:21) at BaseChartDirective.getChartBuilder (http://localhost:3000/node_modules/ng2-charts/components/charts/charts.js:73:16) at BaseChartDirective.refresh (http://localhost:3000/node_modules/ng2-charts/components/charts/charts.js:114:27) at BaseChartDirective.ngOnInit (http://localhost:3000/node_modules/ng2-charts/components/charts/charts.js:18:18) at Wrapper_BaseChartDirective.detectChangesInInputProps (/ChartsModule/BaseChartDirective/wrapper.ngfactory.js:89:53) at _View_HomeComponent0.detectChangesInternal (/AppModule/HomeComponent/component.ngfactory.js:74:32) at _View_HomeComponent0.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9305:18) at _View_HomeComponent0.DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9410:48) at _View_HomeComponent_Host0.AppView.detectViewChildrenChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9331:23) at _View_HomeComponent_Host0.detectChangesInternal (/AppModule/HomeComponent/host.ngfactory.js:33:8)"

Я не уверен, куда идти отсюда. Я опубликовал вопрос о ng2-диаграммах gihub repo. Я застрял, и я буду очень благодарен за вашу помощь.

+0

привет вы можете показать мне утешать выход this.pieChartLabels = _.keys (this.hotelCountByCity); this.pieChartData = _.values ​​(this.hotelCountByCity); вы здесь ошибаетесь. его не в формате, который требуется ng2chart. если возможно, добавьте plnkr также –

+0

Таблицы ng2-chart имеют тип string [] и данные числа []. Я использовал этот же код перед обновлением библиотеки ng2-chart и окончательной версии углового 2. Эта проблема возникла, когда я обновил приложение. –

+0

Я использую ng2-диаграмму с угловыми 2.4.1 и ng2-диаграммами: 1.4.4. ваша метка пирога и данные должны быть в этой форме pieChartLabels: string [] = ['string1', 'string2', 'string3']; но я, если вы используете _.key, будет производить что-то вроде 0: 'string1', но мы хотим, чтобы строка string1 не требовалась. вы можете использовать foreach и нажимать все эти значения строковых данных, используя массив push в переменной, а затем присваивать pieChartLabels. –

ответ

0

Я провел некоторое исследование в Интернете и прочитал документацию. Я не мог найти определенного ответа на мою проблему. Процесс После работал для меня:

  1. Я понижен chart.js от 2.4.0 до 2.3.0
  2. Я добавил логический мой компонент, чтобы указать данные были получены от RESTApi или нет. Я использовал этот флаг для отображения холста с помощью * ngIf.

HTML разметка выглядит следующим образом:

<canvas 
      baseChart 
      class="chart" 
      [data]="data.pieChartData" 
      [labels]="data.pieChartLabels" 
      [chartType]="data.pieChartType" 
      (chartHover)="chartHovered($event)" 
      (chartClick)="chartClicked($event)" 
      *ngIf="isDataAvailable" 
      > 
    </canvas> 
+0

поэтому проблема заключается в том, что время инициализации компонента не было данных в диаграмме? вот почему вы используете boolean. ? –

+0

Странно, да. Но эта проблема не была там. –

+0

Вот почему сэр я попросил вас сохранить значения по умолчанию pieChartLabels: string [] = ['loading']; public pieChartData: number [] = [100]; в начале компонента, чтобы вы не сталкивались с этой ошибкой. можете ли вы попробовать то же самое с 2.4.0 с установкой начального значения. –

Смежные вопросы