我在使用flask与angular全栈开发时,想使用echarts进行绘图(年份数量折线图),但是出现了如下问题
import { Component ,OnInit} from '@angular/core';
import * as echarts from 'echarts';
import {FilmsService} from "./films.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
console = console;
title = 'Angular教程';
options:any;
op :any
constructor(private filmsService:FilmsService) {
}
getyear():any {
this.filmsService.getYearcount().subscribe(
(res)=>{this.options = res}
);
}
ngOnInit(): void {
this.getyear()
this.options = {
xAxis: {
type: 'category',
data: Object.keys(this.options),
},
yAxis: {
type: 'value'
},
series: [
{
data: Object.values(this.options),
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
}
}
这是后端代码
该回答引用ChatGPT
从错误信息可以看出,在ngOnInit方法中,调用Object.keys(this.options)时,this.options为undefined,导致报错。
原因可能是:
代码如下:
import { Component ,OnInit} from '@angular/core';
import * as echarts from 'echarts';
import {FilmsService} from "./films.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
options:any;
constructor(private filmsService:FilmsService) {
}
getYear() {
try {
const result = this.filmsService.getYearCount();
if (result) {
result.subscribe(
(res)=>{this.options = res}
);
}
} catch (err) {
console.log(err);
}
}
ngOnInit(): void {
this.getYear();
setTimeout(() => {
if (this.options) {
this.options = {
xAxis: {
type: 'category',
data: Object.keys(this.options)
},
yAxis: {
type: 'value'
},
series: [
{
data: Object.values(this.options),
type: 'line'
}
]
};
}
}, 1000);
}
}