[英]How to integrate d3js into Angular correctly?
我想用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');
});
}
}
你可以嘗試這個
function (d:any)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.