我正在尝试将数据从谷歌电子表格读取到chart.js,但我在弄清楚如何以 Angular 绘制可观察到的响应时遇到问题。
我希望它能读出折线图,但我不确定格式是否正确。我可以得到一些关于如何修复它的指示,以便我的图表显示。它给我一个错误:类型 IArea[] 上不存在属性区域。
对于我的服务,我有:
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { IArea } from './area';
@Injectable({
providedIn: 'root'
})
export class AreaService {
private areaUrl = "https://docs.google.com/spreadsheets/d/1_FJE8fq2bZ-WgDIY2rEPG3Ml__ypDJBD71pGVeElvGY/edit?usp=sharing"
constructor(private http: HttpClient) { }
getArea(): Observable<IArea[]> {
return this.http.get<IArea[]>(this.areaUrl).pipe(map(response => response.area));
}
}
组件:
import { ChartsModule} from 'ng2-charts'
import * as Chart from 'chart.js';
import { AreaService } from './area.service';
import { IArea } from './area';
@Component({
selector: 'app-widget-area',
templateUrl: './area.component.html',
styleUrls: ['./area.component.scss']
})
export class AreaComponent implements OnInit {
area:IArea[];
httpService: any;
areaService: any;
LineChart: Chart;
errorMessage:string;
constructor(private_areaService:AreaService) { }
ngOnInit() {
this.LineChart = new Chart('lineChart', {
type: 'line',
data: {
labels: ["2009", "2010", "2011", "2012", "2013","2014","2015","2016","2017","2018","2019"],
datasets: [{
label: " ",
data: this.areaService.getArea().subscribe(
area => this.area=area,
error => this.errorMessage =<any>error
),
fill:false,
lineTension:0.2,
borderColor:"black",
borderWidth: 1
}]
},
options: {
title:{
text:"Line Chart"
}
}
});
}
}
指定值:
Date: Date;
Alloc: number;
}
Google 电子表格:
2009 23
2010 20
2011 30
2012 40
2013 24
2014 23
2015 23
2016 56
2017 32
2018 34
2019 34
最佳答案
创建一个在获取用于创建图表的数据时调用的函数:
createChart() {
this.LineChart = new Chart('lineChart', {
type: 'line', data: {
labels: ['2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019'],
datasets: [{
label: ' ',
data: this.area,
fill: false,
lineTension: 0.2,
borderColor: 'black',
borderWidth: 1
}
]
}, options: {
title: {
text: 'Line Chart'
}
}
}
);
}
并调用数据:
ngOnInit() {
this.areaService.getArea().subscribe(area => {
this.area = area;
this.createChart();
}, error => {
this.errorMessage = error;
}
);
}
您的服务将是:
getArea() {
return this.http.get<IArea[]>(this.areaUrl);
}
您还可以从数据中动态获取标签,而不是静态放置标签。
关于javascript - 我怎样才能绘制出我的可观察到的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59326900/