我正试图用firestore数据生成一个图,我使用了ng2charts,我编写了代码,但它向我发送了以下错误。类型"unknown"上不存在属性"data"。这使我在项目.data 中出现错误
类型"unknown"上不存在属性"datatime"。这使我在项目.datatime 中出现错误
如何解决?
这是我的组件:
labelsdatatimeArray: any = [];
dataArray: any = [];
@ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;
constructor(public navCtrl: NavController, private firestore: AngularFirestore) { }
ngOnInit() {
this.firestore.collection('/ELGeneraciónEmpleosFormalesDiciembreCadaAño/').get().toPromise().then((snapshot) => {
snapshot.docs.forEach(doc => {
let item = doc.data();
let data = item.data;
this.dataArray.push(data);
let datatime = item.datatime;
this.labelsdatatimeArray.push(datatime);
});
});
}
public barChartOptions: ChartConfiguration['options'] = {
responsive: true,
scales: {
x: { ticks: {
stepSize: 1,
maxRotation: 60,
minRotation: 60,
autoSkip: false
}},
y: {
min: -40
}
},
plugins: {
legend: {
display: true,
},
datalabels: {
anchor: 'end',
align: 'end'
}
}
};
public barChartType: ChartType = 'bar';
public barChartPlugins = [
DataLabelsPlugin
];
public barChartData: ChartData<'bar'> = {
labels: [this.labelsdatatimeArray],
datasets: [
{ data: [this.dataArray],
label: '' },
]
};
// events
public chartClicked({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
console.log(event, active);
}
public chartHovered({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
console.log(event, active);
}
如果item
被推断为unknown
值,那么最好添加类型检查,而不是使用any
来避免编译错误。
您可以使用以下类型的防护装置:
let item = doc.data(); // assuming item is unknown
// In the following code I dont know what is the type of the data in your case
// so you can declare a specific type that you are expecting instead of any
let data =
item && typeof item === "object" && "data" in item
? (item! as { data: any /** Use specific type here */ }).data
: null;
if(!data){
// handle null data
// However, if you sure you will get a value in data then no need to add this if check
}
// same for datetime
let datetime =
item && typeof item === "object" && "datetime" in item
? (item! as { datetime: any }).datetime
: null;
if(!datetime){
// handle null datetime
// However, if you sure you will get a value in datetime then no need to add this if check
}