Ng-alain中G2图表加载动态数据

2021-03-18  本文已影响0人  成长开发者

在做图表展示的时候,大部分是采用异步请求,获取图表数据。页面上如果有查询功能,在异步请求后,又需要动态更新当前图表。

代码如下

<!-- HTML 部分 -->
<!-- 查询表单 -->
<nz-card class="animated fadeIn">
    <sf style="float:right;margin-left: 20px;" #sfProgramSearch mode="default" layout="inline" firstVisual="false"
        [schema]="schemaData.search" [formData]="tableParams" (formSubmit)="onSearchSubmit($event)" class="search-form" [button]="null">
        <nz-form-item class="sf-btns">
          <div class="ant-form-item-control">
            <button type="submit" nz-button [nzType]="'primary'" nzSize="default">查询</button>
          </div>
        </nz-form-item>
      </sf>
  </nz-card>
  <!-- 查询表单 end -->
  <nz-spin nzTip="加载中..." [nzSpinning]="loadingChart">
    <nz-card [nzBordered]="false">
      <div nz-row>
        <!-- 使用自定义图表 -->
        <!-- 我使用的是 G2 v3.x 版本,在使用异步请求数据后,图表不会自动变化,故采用自定义图表的方式 -->
        <g2-custom (render)="render($event)"></g2-custom>
      </div>
    </nz-card>
    <nz-result *ngIf="isShow" nzStatus="404" nzTitle="" nzSubTitle="暂未开放...">
      <div nz-result-extra>
      </div>
    </nz-result>
  </nz-spin>
// component.ts 部分
import { ElementRef, ViewChild } from '@angular/core';
import { Component, Injector, OnInit, ChangeDetectionStrategy } from '@angular/core';
import * as differenceInCalendarDays from 'date-fns/difference_in_calendar_days';
import { IndexControl } from '@core';
import { map, timeout } from 'rxjs/operators';
const changeDetection = ChangeDetectionStrategy.OnPush;
@Component({
  selector: 'app-program-chart-history',
  templateUrl: `./history.component.html`,
  styles: [``],
  changeDetection,
})
export class ProgramChartHistoryComponent extends IndexControl implements OnInit {
  loadingChart: boolean = true; // 页面加载中状态
  chartObject: any; // 变量保存图表对象,方便数据多次变化 
  isShow: boolean = false; // 控制展示 404 页面
  constructor(protected injector: Injector) {
    super(injector);
    super.__init__(this, null, { changeDetection });
  }
  ngOnInit() {
    super.ngOnInit();
    this.modalData.title = '节目发送详情';
   // 动态表单的字段属性设置
    this.schemaData = {
      search: {
        properties: {
          search_date: {
            type: 'string',
            title: '查询日期',
            ui: {
              widget: 'date',
              disabledDate: (current: Date) => {
                return differenceInCalendarDays(current, new Date()) > 0;
              },
            },
          },
          program_ids: {
            type: 'string',
            title: '选择节目',
            ui: {
              placeholder: '请选择节目',
              width: 700,
              widget: 'select',
              mode: 'tags',
              allowClear: true,
              asyncData: (res: any) => {
                return this.httpSrv.get('/programInfo2', { list: true }).pipe(
                  map((resp: any) => {
                    let result = [];
                    resp.data.list.forEach(element => {
                      result.push({
                        label: element.program_title,
                        value: element.program_id,
                      });
                    });
                    return result;
                  }),
                );
              },
            },
          },
        },
        ui: {},
      },
    };
  }
  // 自定义图表的函数
  render(el: ElementRef) {
    // 异步请求数据
    this.freeData.getData = this.httpSrv.post('Statistics/dayProgram').subscribe((res: any) => {
      this.loadingChart = false;
      this.cdr.detectChanges();
      if (false == res.data) {
        this.isShow = true;
        return;
      }
      let data = [];
      let height = 500; // 根据返回数据数量,动态变化高度
      if (0 < res.data.length) {
        data = res.data;
        if (10 < res.data.length) {
          height = res.data.length * 20;
        }
      }
      // 实例化图表的时候,赋值给类变量
      // 以下部分的图表代码,可以直接拿官方示例的代码
      this.chartObject = new G2.Chart({
        container: el.nativeElement, // 注意修改container 
        forceFit: true,
        height: height,
        padding: [0, 90, 20, 152],
      });
      this.chartObject.source(data);
      this.chartObject.axis('program_title', {
        label: {
          textStyle: {
            fill: '#aaaaaa',
            fontSize: 12,
          },
        },
      });
      this.chartObject.axis('value', {
        label: {
          textStyle: {
            fill: '#aaaaaa',
            fontSize: 12,
          },
        },
        title: {
          offset: 30,
          textStyle: {
            fontSize: 14,
            fontWeight: 300,
          },
        },
      });
      this.chartObject.legend({
        position: 'right-bottom',
      });
      this.chartObject.coord().transpose();
      this.chartObject
        .interval()
        .position('program_title*value')
        .color('type')
        .opacity(1)
        .adjust([
          {
            type: 'dodge',
            marginRatio: 0,
          },
        ]);
      this.chartObject.render();
    }, (error: any)=>{
      this.loadingChart = false;
      this.cdr.detectChanges();
    });
  }
  // 节目查询函数
  onSearchSubmit($event) {
    this.loadingChart = true;
    this.freeData.getData = this.httpSrv.post('Statistics/dayProgram', $event).subscribe((res: any) => {
      this.loadingChart = false;
      this.cdr.detectChanges();
      if (false == res.data) {
        this.isShow = true;
        return;
      }
      let data = [];
      let height = 500;
      if (0 < res.data.length) {
        data = res.data;
        if (10 < res.data.length) {
          height = res.data.length * 20;
        }
      }
      // 异步请求数据后,调用类图表对象变量,使用 changeData(data) 修改图表数据
      this.chartObject.changeData(data);
      // 使用以下方式修改图表的高度
      // 具体其他属性,可以 console.log(this.chartObject) 在控制台查看
      this.chartObject._attrs.height = height;
      this.chartObject.forceFit();
    }, (error: any)=>{
      this.loadingChart = false;
      this.cdr.detectChanges();
    });
  }
}
上一篇 下一篇

猜你喜欢

热点阅读