import {Component, OnInit} from '@angular/core'; import {MovieService} from "../movie.service"; @Component({ selector: 'app-count_by_year', templateUrl: './count_by_year.component.html', styleUrls: ['./count_by_year.component.css'] }) export class Count_by_yearComponent implements OnInit{ movies:any[]=[] options:any; constructor(private movieService :MovieService) {} ngOnInit() {this.movieService.count_by_year().subscribe((data:any[])=>{ this.movies = data; console.log(this.movies)}); this.options = { title: { text:'华语电影年产量趋势图', left:'center', }, dataset:[{source:this.movies}], xAxis: { type: 'category', name:'年份', data:[1900, 1913, 1916, 1923, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018] }, yAxis: { type:'value', name:'产量', }, series: [ { data:[1, 1, 1, 1, 4, 3, 1, 3, 5, 5, 6, 2, 9, 10, 6, 8, 12, 8, 11, 5, 9, 5, 1, 1, 1, 1, 18, 18, 27, 40, 36, 66, 71, 53, 85, 131, 98, 109, 125, 140, 146, 113, 143, 117, 119, 108, 132, 169, 174, 172, 156, 154, 159, 195, 165, 192, 181, 210, 212, 239, 228, 217, 161, 150, 144, 145, 163, 170, 184, 197, 149, 196, 206, 192, 149, 111, 108, 99, 141, 188, 172, 162, 134, 155, 147, 166, 173, 184, 221, 319, 371, 475, 412, 542, 823, 1427, 1710, 1144], type: 'line', } ] } } }优化以上代码,后端数据量很大,不希望这样手动输入数据,该怎么办?
时间: 2023-07-02 07:14:39 浏览: 53
可以通过请求后端接口来获取数据,而不是手动输入数据。在 ngOnInit 方法中,可以先调用一个新的方法来请求数据,然后在获取到数据后再构建 options 对象。
具体实现如下:
```
import {Component, OnInit} from '@angular/core';
import {MovieService} from "../movie.service";
@Component({
selector: 'app-count_by_year',
templateUrl: './count_by_year.component.html',
styleUrls: ['./count_by_year.component.css']
})
export class Count_by_yearComponent implements OnInit{
movies:any[]=[];
options:any;
constructor(private movieService :MovieService) {}
ngOnInit() {
this.getMovieData();
}
// 请求数据
getMovieData() {
this.movieService.count_by_year().subscribe((data:any[])=>{
this.movies = data;
console.log(this.movies)
this.buildOptions();
});
}
// 构建 options 对象
buildOptions() {
this.options = {
title: {
text:'华语电影年产量趋势图',
left:'center',
},
dataset:[{source:this.movies}],
xAxis: {
type: 'category',
name:'年份',
data: this.movies.map(item => item.year)
},
yAxis: {
type:'value',
name:'产量',
},
series: [
{
data: this.movies.map(item => item.count),
type: 'line',
}
]
}
}
}
```
在 `getMovieData()` 方法中,先调用 `movieService.count_by_year()` 方法来请求数据,获取到数据后再调用 `buildOptions()` 方法来构建 options 对象。在构建 options 对象时,可以利用 `Array.map()` 方法来从 `movies` 数组中提取出年份和产量数据。这样就可以动态地获取后端数据并显示在图表中了。