如何解决使用D3库将数据传递到angular中的子组件的问题

时间:2019-04-07 18:17:17

标签: d3.js angular-ngfor

我是d3.js库的新手,我试图构建一个非常简单的角度应用程序,在其中显示一个条形图,其中使用* ngFor指令创建了多个子组件,而不是将动态数据传递给子组件。将数据传递给所有子组件时,只有第一个组件接收所有传递的数据,其余的保持为空。

似乎没有任何作用。

应用组件

  _trucksUrl = 'http://localhost:3000/trucks';

  trucksInformation;

  constructor(private http: HttpClient){}

  getTrucks(){
    return this.http.get<any>(this._trucksUrl);
  }

  ngOnInit(){
    this.getTrucks().subscribe((response) => {
      this.trucksInformation = JSON.parse(response.trucks);
      console.log(this.trucksInformation);
    },
    error => {
      console.error(error);
    })
  }
}

应用程序组件HTML

<div>
   <app-truckdata *ngFor="let truck of trucksInformation" [initialTruck] = "truck"></app-truckdata>
</div>

TruckComponent

import { Component, OnInit, AfterViewInit, Input, AfterContentInit } from '@angular/core';
import * as d3 from 'd3';

@Component({
  selector: 'app-truckdata',
  templateUrl: './truckdata.component.html',
  styleUrls: ['./truckdata.component.scss']
})
export class TruckdataComponent implements OnInit, AfterContentInit {

  @Input() initialTruck;

  truck = [];

  constructor() { }

  ngOnInit() {
    for(let key in this.initialTruck){
      if(typeof this.initialTruck[key] === 'object' || key === 'StationId') {
        continue;
      } else {
        let propObj = {
          propname: key,
          value: +this.initialTruck[key]
        };
        this.truck.push(propObj);
      }
    }
  }

  ngAfterContentInit() {
    let margin = { top: 30, right: 30, bottom: 70, left: 130 },
      width = 460 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

    let svg = d3.select(".truck-info")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

    let x = d3.scaleLinear()
      .domain([0, 10000])
      .range([0, width]);
    svg.append('g')
      .attr('transform', `translate(0, ${height})`)
      .call(d3.axisBottom(x))
      .selectAll("text")
      .attr("transform", "translate(-10,0)rotate(-45)")
      .style("text-anchor", "end");

    let y = d3.scaleBand()
      .range([0, height])
      .domain(this.truck.map(function (d) { return d.propname; }))
      .padding(.1);
    svg.append("g")
      .call(d3.axisLeft(y));

    svg.selectAll('rect')
      .data(this.truck)
      .enter()
      .append('rect')
      .attr('x', x(0))
      .attr('y', function (d) { return y(d.propname) })
      .attr("width", function (d) { return x(d.value); })
      .attr("height", y.bandwidth())
      .attr("fill", "#69b3a2")
  }

}

我希望获得许多子组件,每个子组件都包含一个条形图,但是我收到的是一个子组件,所有条形图和所有其余子组件均保持空白。 example

0 个答案:

没有答案