【发布时间】:2018-12-19 16:28:55
【问题描述】:
我在这里有 stackbiltz - https://stackblitz.com/edit/lable-line-break-vaszab?file=src/app/app.component.ts
我在 Angular 应用中有一个 d3 条形图。
使用在创建 z 轴刻度时调用的函数将 x 轴标签分成两行
private insertLinebreak(d) {
let labels = d3.select(this);
let words = d;
console.log("Label:", labels.html());
labels.text('');
let index = words.indexOf(' ', words.indexOf(' ') + 1)
let title = words.substr(0, index)
let subtitle = words.substr(index + 1)
let tspantitle = labels.append('tspan').text(title)
let tspansubtitle = labels.append('tspan').text(subtitle)
tspantitle
.attr('x', 0)
.attr('dy', '15')
.attr('class', 'x-axis-title');
tspansubtitle
.attr('x', 0)
.attr('dy', '16')
.attr('class', 'x-axis-subtitle');
};
函数使用'this'来选择调用函数的'g'(但在d3中我认为它选择了整个svg)
此代码在 stackblitz 中有效,但在我的实际代码中出现错误
Argument of type 'this' is not assignable to parameter of type 'BaseType'.
我知道这不是很有帮助
我认为这与 Typescript 及其处理“this”的方式有关
有谁知道为什么会发生这种情况以及我该如何解决这个问题。
【问题讨论】:
-
这听起来像是与 TypeScript 相关的 type 错误,而且 D3 不是 TypeScript 库。您可以通过将
npm install @types/d3 --save添加到您的项目来安装类型支持。BaseType是 D3 类型的一部分,您可以查看上述包中的.d.ts文件,以了解d3.select的类型签名是什么。您需要将this转换为该类型,但这并不意味着您的代码可以正常工作。这只是 TypeScript 的输入错误。 -
是的,我认为它与 Typescript 有关。我在应用程序中安装了 d3 类型。实际的应用程序可以工作,但这个错误意味着我无法将其推送到生产环境。
标签: angular typescript d3.js