首页 > 解决方案 > 如何正确地将 d3js 集成到 Angular 中?

问题描述

我想用 d3 读取 JSON 文件并将其集成到 Angular 中。只有使用 d3 我的代码才能正常工作,但如果我添加 Angular,它会发现错误:

src/app/app.component.ts(50,64) 中的错误:错误 TS2339:“HierarchyNode”类型上不存在属性“x0”。src/app/app.component.ts(50,70):错误 TS2339:“HierarchyNode”类型上不存在属性“y0”。src/app/app.component.ts(54,44):错误 TS2339:“HierarchyNode”类型上不存在属性“x1”。src/app/app.component.ts(54,51):错误 TS2339:“HierarchyNode”类型上不存在属性“x0”。src/app/app.component.ts(55,45):错误 TS2339:“HierarchyNode”类型上不存在属性“y1”。src/app/app.component.ts(55,52):错误 TS2339:“HierarchyNode”类型上不存在属性“y0”。

    import { Component, OnInit } from '@angular/core';
    import * as d3 from 'd3';
    import treemapOwnTiling from './treemapOwnTiling.js';

    interface ResponseData {
       value: number;
       x0: number;
       y0: number;
       x1: number;
       y1: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'treemap';

  ngOnInit() {

d3.json<ResponseData>('../assets/test2.json')
.then((data) => {

  const w = window.innerWidth - 20;
  const h = window.innerHeight - 20;

  const treemapLayout = d3.treemap()
    .size([w, h])
    .paddingOuter(10);

  console.log(w);
  console.log(h);

  const root = d3.hierarchy(data);

  root.sum(function (d) {
    return d.value;
  });

  treemapLayout.tile(treemapOwnTiling);
  treemapLayout(root);

  const nodes = d3.select('svg g')
    .selectAll('g')
    .data(root.descendants())
    .enter()
    .append('g')
    .attr('transform', function (d) { return 'translate(' + [d.x0, d.y0] + ')'; });

  nodes
    .append('rect')
    .attr('width', function (d) { return d.x1 - d.x0; })
    .attr('height', function (d) { return d.y1 - d.y0; });

  /*nodes
    .append('text')
    .attr('dx', 4)
    .attr('dy', 10)
    .attr('class', 'small')
    .text(function (d) {
      return d.data.name;
    })*/

    const ufo = nodes
      .append('foreignObject')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml');

    const div = ufo
      .append('xhtml:div')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml');

    div
      .append('xhtml:i')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml')
      .attr('class', 'fas fa-pencil-alt')
      .append('xhtml:i')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml')
      .attr('class', 'fas fa-flag')
      .append('xhtml:i')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml')
      .attr('class', 'fas fa-bell')
      .append('xhtml:i')
      .attr('xmlns', 'http://www.w3.org/1999/xhtml')
      .attr('class', 'fas fa-user');
});
  }
}

标签: javascriptjsonangulard3.js

解决方案


你可以试试这个

function (d:any)

推荐阅读