ng2-диаграммы, изменяющие цвет диаграммы, делают диаграмму странной - PullRequest
0 голосов
/ 07 сентября 2018

Я искал способ изменить цвет индикатора моей гистограммы в течение нескольких дней. Это ионно-угловое приложение 3.9.2. Я перепробовал множество обходных путей, опубликованных здесь, но безрезультатно. Я нашел свой собственный способ сделать это, но Barchart ведет себя очень странно. Во-первых, мне пришлось поместить кнопку, чтобы перезапустить функцию с вызовом API, который выводит данные на мой график, потому что он не будет показывать, если функция запускается только один раз. С другой стороны, столбцы становятся действительно тонкими.

График, если я не использую флаг показа (загружается нормально) https://user -images.githubusercontent.com / 16280628 / 45188356-56c57b80-b20a-11e8-879b-a6d1ed7430d1.png

График, если я делаю (берет кнопку, чтобы загрузить) https://user -images.githubusercontent.com / 16280628/45188227-e0287e00-b209-11e8-8e05-ab6568eeb6d3.png

Спасибо, любая помощь будет высоко ценится

Информация:

  "dependencies": {
    "@angular/animations": "5.2.11",
    "@angular/common": "5.2.11",
    "@angular/compiler": "5.2.11",
    "@angular/compiler-cli": "5.2.11",
    "@angular/core": "5.2.11",
    "@angular/forms": "5.2.11",
    "@angular/http": "5.2.11",
    "@angular/platform-browser": "5.2.11",
    "@angular/platform-browser-dynamic": "5.2.11",
    "@ionic-native/core": "~4.11.0",
    "@ionic-native/splash-screen": "~4.11.0",
    "@ionic-native/status-bar": "~4.11.0",
    "@ionic/storage": "2.1.3",
    "chart.js": "^2.7.2",
    "cordova-android": "~7.0.0",
    "cordova-plugin-device": "2.0.2",
    "cordova-plugin-ionic-keyboard": "^2.0.5",
    "cordova-plugin-ionic-webview": "^2.0.0",
    "cordova-plugin-splashscreen": "5.0.2",
    "cordova-plugin-whitelist": "1.3.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "ng2-charts": "^1.6.0",
    "rxjs": "5.5.11",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.26"

Код:

HTML:

   <div style="display: block" *ngIf="show">
    <canvas baseChart height="" 
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [colors]="barChartColors"
            [legend]="barChartLegend"
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>

JS:

public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true,
legend: {display:false},
scales: {
yAxes: [{id: 'y-axis-1', type: 'linear', position: 'left', ticks: {min: 0, max:60}}]
}
};

public barChartLabels:string[] = ['L', 'M', 'M', 'J', 'V', 'S', 'D'];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;

public barChartData:any[] = [
{data: [0]}
]; 

public barChartColors:Array<any> = [{}];
leerDatos() {       //FUNCTION THAT MAKES THE API CALL

//clear out the previous array contents
this.info_items = [];
this.datos_actividad = [];
this.datos_color = [];
this.errorConexion = false;

//Create the loading indicator
let loader = this.loadingCtrl.create({
content: "Obteniendo perfil de usuario..."
});

//Show the loading indicator    
loader.present();

this.serviceWiseapp.obtenerActividadFisica().then(
data => {

loader.dismiss();


if (data) {

//cWe have data, so lets do something with it
this.info_items = this.formatInfoItems(data.actividadFisica);

for(let i=0; i < this.info_items.length; i++){
this.datos_actividad[i] = this.info_items[i].duracionActividadFisica;
}
this.barChartData = this.datos_actividad;

this.barChartColors[0].backgroundColor = 

this.obtenerColores(this.info_items);  // Only way ive 
                                                                                                    //found to change color dinamically
    this.errorConexion = false;



// console.log(this.barChartData);

this.show=true;
//this.barChartColors = this.datos_color;
} else {
//This really should never happen
this.errorConexion = true;
}

},
error => {

//Hide the loading indicator
loader.dismiss();
this.errorConexion = true;
}
);
}

...

private obtenerColores(info_items:any){
let tmpArray:any = [];

if (info_items) {

for (let i = 0; i < info_items.length; i++) { 
if(info_items[i].duracionActividadFisica >= 35){
tmpArray.push(          
'rgba(0, 192, 0, 0.6'
);  
}else if(info_items[i].duracionActividadFisica >= 20){
tmpArray.push(          
'rgba(255,255,0,0.6)'
);  
}else {
tmpArray.push(          
'rgba(255, 25, 25, 0.6)'
);  
}    
}
};

return tmpArray;
}

Chart

...