简体   繁体   English

我无法在angular / d3js中访问_groups属性

[英]I can't access the _groups property in angular/d3js

I have a problem accessing my "_groups" property with the following code: 我在使用以下代码访问“ _groups”属性时遇到问题:

function mouseDate(scale){ 
        var g = d3.select("#group")._groups[0][0]

        var x0 = scale.invert(d3.mouse(g)[0]);

        console.log(x0);
    }

Result of my console.log: 我的console.log结果:

Selection {_groups: Array(1), _parents: Array(1)}
  _groups: Array(1)
    0: Array(1)
      0: g#group

When I compile the code I have the following error : 编译代码时,出现以下错误:

D:/Documents/starter-propre-angular4/src/app/pages/graphe-page/graphe.page.ts (782,32): Property '_groups' does not exist on type 'Selection<BaseType, {}, HTMLElement, any>'.

So my question is: Is there a solution to get the information in "_groups" all year round knowing that I am evolving into TypeScript using d3js 所以我的问题是:是否知道我正在使用d3js升级为TypeScript,是否有一种解决方案可以全年获取“ _groups”中的信息。

The _groups property is a private member of a Selection object and should as such not be accessed directly. _groups属性是Selection对象的私有成员,因此不应直接访问。 (Side note: it is common convention in JavaScript that any member starting with an underscore denotes a private member. See, eg, "Underscore prefix for property and method names in JavaScript" ). (附带说明:JavaScript中的惯例是,任何以下划线开头的成员都表示私有成员。例如,参见“ JavaScript中属性和方法名称的下划线前缀” )。

Since the property is considered private it is not part of the public interface and is therefore not included in the TypeScript type declaration for the d3-selection module. 由于该属性被视为私有属性,因此它不是公共接口的一部分,因此不包含在d3选择模块的TypeScript类型声明中。 Hence, you get the compiler error you witnessed. 因此,您将看到见证的编译器错误。 Although this actually will work in pure JavaScript the TypeScript compiler did exactly what it is supposed to do—namely, prevent you from doing some unsafe stuff. 尽管这实际上可以在纯JavaScript中运行,但TypeScript编译器确实可以实现它应做的工作-即,防止您做一些不安全的事情。

Looking at the code you posted, though, it becomes apparent that you are not interested in the _groups property itself but rather in _groups[0][0] which internally refers to the first node of the selection. 但是,看一下您发布的代码,您显然对_groups属性本身不感兴趣,而对_groups[0][0]感兴趣,该内部引用选择的第一个节点。 Fortunately, the selection.node() method will return exactly that first element. 幸运的是, selection.node()方法将完全返回该第一个元素。 You can do it like this: 您可以这样做:

function mouseDate(scale){ 
  var g = d3.select("#group").node();
  var x0 = scale.invert(d3.mouse(g)[0]);
  console.log(x0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM