我正在使用链接中的代码在d3地图中实现工具提示 http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922
当我在angular 2 typescript文件中编写相同的代码时。我收到错误:
无法读取未定义
的属性“转换”它基本上无法找到d3.event(将其设为null),这在javascript代码中不会发生。 我的代码在ngAfterViewInit
ngAfterViewInit() {
this.tooltip = d3.select("map-tag")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
this.svgContainer = d3.select("map-tag").append("svg")
.attr("width", this.width)
.attr("height", this.height)
.style("border", "2px solid steelblue")
.call(this.zoom);
this.usaSVG = this.svgContainer
.append("path")
.attr("d", this.geoPath(this.usaFeatureCollection))
.style({ fill: "none", stroke: "black" });
this.geoPoint1 = {
"type": "MultiPoint", "coordinates": [[-80.6665134, 35.0539943]]
};
this.div = d3.select("map-tag")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
this.pointPath = this.svgContainer.append("path").attr("d", this.geoPath(this.geoPoint1)).style("stroke", "#FFFFFF")
.on('mouseover', function (d, i) {
this.div.transition()
.duration(200)
.style("opacity", .9);
this.div.text("sample text")
.style("left", (d3.event.x) + "px") // I get error here
.style("top", (d3.event.y - 28) + "px");
})
.on('mouseout', function (d, i) { d3.select(this).style({ fill: 'black' }); });
}
/* Style for Custom Tooltip */
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: white;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
答案 0 :(得分:1)
您需要从d3导入事件,如下所示:
Import {event, BaseEvent} from "d3-selection"
答案 1 :(得分:0)
您的代码
this.div.transition()
在函数内部可能会因调用this
而失去.on('mouseover', (d, i) => {
this.div.transition()
.duration(200)
.style("opacity", .9);
this.div.text("sample text")
.style("left", (d3.event.x) + "px") // I get error here
.style("top", (d3.event.y - 28) + "px");
})
。
使用箭头
new webpack.NormalModuleReplacementPlugin(new RegExp('path/to/B'), function(result) {
result.request = result.request.replace("projectB", "projectA");
}),
https://egghead.io/lessons/typescript-catch-unsafe-use-of-this-in-typescript-functions