d3.js 无法读取未定义的属性(阅读'append')不确定原因?[duplicate]

xuo3flqw  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(176)

此问题已存在

The barchart is not being displayed in the local server site?
三个月前关门了。
我在d3.js中使用了Angular TypeScript。我创建了一个条形图,但它没有显示出来,不知道为什么。我创建了私有类并将它们实现到ngOnInit()类中,但当我在服务器上运行它时,没有任何内容,并且是空白的。在终端上,它没有显示任何问题,但我不确定为什么它没有显示。我不确定是否必须将其调用到bar-char. component中。html。我创建了一个小数据集,只是为了看看条形图是否可以可视化。这是Angular/TypeScript和d3.js的新手。下面是我的代码:

  1. export class BarChartComponent implements OnInit
  2. {
  3. private svg:any;
  4. private dataSet = [10,20,30,32,47,50,76];
  5. private margin = 50;
  6. private height = 100 - (this.margin * 2);
  7. private width = 200 - (this.margin * 2);
  8. public createSvg(): void{
  9. var svg = d3.select('barchart')
  10. .append('svg')
  11. .attr("width", this.height + (this.margin * 2)
  12. )
  13. .attr("height", this.height + (this.margin *
  14. 2))
  15. .append('g')
  16. .attr('transform', 'translate(' + this.margin
  17. + "," + this.margin + ')');
  18. d3.select('barchart');
  19. }
  20. //x axis band scale
  21. private drawBars(dataSet: any[]): void{
  22. const xAxis = d3.scaleBand()
  23. .range([0, this.width])
  24. .domain(dataSet.map(d => d.Framework))
  25. .padding(0.2);
  26. // drawing the x-axis
  27. this.svg.append('g')
  28. .attr("transform", "translate(0," +
  29. this.height + ")")
  30. .call(d3.axisBottom(xAxis))
  31. .selectAll("text")
  32. .attr("tranform"
  33. ,"translate(-10,0)rotate(-45)")
  34. .style("text-anchor", "end");
  35. const yAxis= d3.scaleLinear()
  36. .domain([0, 100])
  37. .range([this.height, 0]);
  38. this.svg.append("g")
  39. .call(d3.axisLeft(yAxis));
  40. //creation of bar graph and fill in the bars
  41. this.svg.selectAll("bars")
  42. .data(dataSet)
  43. .enter()
  44. .append("rect")
  45. //.attr("x", d => xAxis(d.Framework))
  46. //.attr("y", d => yAxis(d.Stars))
  47. .attr("width", xAxis.bandwidth())
  48. //.attr("height", (d) => this.height -
  49. yAxis(d.Stars))
  50. .attr("fill", "#d04a35");
  51. }
  52. constructor() { }
  53. ngOnInit(): void {
  54. this.createSvg();
  55. this.drawBars(this.dataSet);
  56. }

在我运行服务器后,我在控制台上得到一个错误,关于它没有阅读append属性。下面是错误消息的图片:ERROR TypeError: cannot read properties of undefined(reading 'append')
有什么好的提示,让未来不会重复同样的错误?我对使用这些技术非常陌生。

waxmsbnn

waxmsbnn1#

我会从调试开始,找出将错误附加到哪个对象上,但有时我会通过添加optional chaining.来处理此类问题
看起来您实际上可能需要在createSvg()中引用全局svg

  1. public createSvg(): void{
  2. this.svg = d3.select('barchart')
  3. ?.append('svg')
  4. .attr("width", this.height + (this.margin * 2)
  5. )
  6. .attr("height", this.height + (this.margin *
  7. 2))
  8. ?.append('g')
  9. .attr('transform', 'translate(' + this.margin
  10. + "," + this.margin + ')');
  11. d3.select('barchart');
  12. }

相关问题