javascript - 如何正确地将 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');
});
}
}
解决方案
你可以试试这个
function (d:any)
推荐阅读
- typescript - 相当于 Go 的 Defer 语句的 TypeScript
- sql - 如何从具有多个时间跨度的单个表中检索重叠的时间范围?
- java - 如何打印一个单词的重复次数
- java - JPA @Version 与 @Transactional 丢失更新
- python - numpy 向量化回归方法 - 单个独立列 (y) 上的多个相关列 (x)
- .net - 在 cosmos db 中按大小获取文档
- javascript - 自定义反应下拉菜单未正确打开关闭
- python - 结束后在进程中启动的线程会发生什么
- powershell - 如何使用 PowerShell 将模块导入 Azure 自动化帐户?
- git - “repo sync”是否等同于“git remote update && git rebase origin/branch”?