代码之家  ›  专栏  ›  技术社区  ›  user9646441

为什么这个svg和数组会在angular中多次启动?

  •  0
  • user9646441  · 技术社区  · 8 年前

    [组件ts]

    import { Component, style } from "@angular/core";
    import { DataService } from '../data.service';
    import d3 = require("d3-3");
    import { Data } from "../data";
    
    @Component({
      selector: 'ts-graph',
      templateUrl: './time-seriesG.component.html',
      styles: [`
        .graph: {padding-left: 20px !important; }
      `]
    })
    export class timeSeriesComponent {
      sym: string[] = [];
      price: any[] = [];
      tStamp: any[] = [];
      data: any[]=[];
      arr: any;
    
      constructor(private dataService: DataService) { }
    
      getData() {
        let i: number;
        this.dataService.getData()
          .subscribe(data => {
        for(i=0;i<Object.keys(data).length;i++){
          this.data.push(data[i])
        }
          });
      }
    
      logV() {
        this.arr = this.data.map((d,i) => ({
          //time: d.time, 
          //sym: d.sym,
          price: d.price, 
          index: i 
        }))
    
        this.arr = this.arr.slice(0,25)
        console.log(this.arr.slice(0,25))
      }
    
      lineGraph() {
        var h=400; 
        var w=350; 
        var lineFun = d3.svg.line()
                        .x(function(d){return d.index*5})
                        .y(function(d){return d.price})
                        .interpolate('linear');
    
        var svg = d3.select('div')
                    .append('svg')
                    .attr('id','LineGraph')
                    .attr('width',w)
                    .attr('height',h);
    
        var viz = svg.append('path')
                     .attr('d',lineFun(this.arr))
                     .attr('stroke','white')
                     .attr('stroke-width',2)
                     .attr('fill','none');
    
      }
    
      ngOnInit() {
        this.getData();
      }
    
    }
    

    [组件.html]

    <h2>Time Series Graph</h2>
    <div>{{logV()}}</div>
    <div>{{lineGraph()}}</div>
    

    我正在尝试获取来自服务的一些数据的简单折线图。由于某些原因,svg组件被多次创建。

    Elements inspection

    另外,我的一个阵列似乎也被多次启动。

    Same Array twice

    我非常感谢您的建议,但请记住,我没有很多使用angular的经验。

    数组格式: enter image description here

    1 回复  |  直到 8 年前
        1
  •  0
  •   Leon    8 年前

    你打电话 lineGraph 从您的角度来看 <div>{{lineGraph()}}</div> 因此,每次触发changedetection时,都会调用该函数,从而产生许多附加的SVG。

    只需在收到数据后调用它一次,您应该只得到一个svg。