关于#typescript#的问题:我在使用flask与angular全栈开发时,想使用echarts进行绘图但数据传输好像出了一点问题

我在使用flask与angular全栈开发时,想使用echarts进行绘图(年份数量折线图),但是出现了如下问题

img


上图可以看出我的数据应该是已经传入网页了

img

img


这是后端截图

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)'
          }
        }
      ]

    };

  }

}


这是后端代码

img


报错如上图
请问应该怎么解决呢?

该回答引用ChatGPT

从错误信息可以看出,在ngOnInit方法中,调用Object.keys(this.options)时,this.options为undefined,导致报错。
原因可能是:

  1. this.getYear()方法中的ajax请求尚未返回,this.options还未被赋值,时undefined。
  2. this.getYear()方法中的ajax请求失败,this.options没有被赋值。

代码如下:

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);
  }

}