【问题标题】:How to implement D3 lasso plugin with Angular 2 and Typescript如何使用 Angular 2 和 Typescript 实现 D3 套索插件
【发布时间】:2017-10-21 09:13:53
【问题描述】:

我正在尝试在使用 Typescript 的 Angular 2 项目中使用由 Speros Kokenes(https://github.com/skokenes/D3-Lasso-Plugin) 创建的套索插件。我的项目中的 D3 v4 工作正常,但是当我尝试添加套索插件时,我遇到了问题,因为它没有 .d.ts 文件。

我试图创建一个无济于事(超出我目前的技能),我试图直接将它作为纯 JS 脚本使用 declare var Lasso: any; 语法。有没有人用 Angular2 实现 D3 插件的例子?

提前致谢。

编辑:我离得更近了一点,能够将插件包含到项目中,并且正在执行代码。但是,该插件引用了 D3.js 核心功能。不幸的是,调用插件时 d3 对象未定义,我的假设是它需要引用 global.d3 引用,但我还没有找到访问它的方法。我回去查看其他 d3 插件以获取如何引用它的线索,但看起来这是唯一的一个。

【问题讨论】:

    标签: angular typescript d3.js typescript-typings d3.js-lasso


    【解决方案1】:

    我正在处理同样的问题。我想出了几个解决方案。

    选项 1

    在你的类中创建一个全局变量。

    import { lasso } from 'd3-lasso';
    
    export class Graph {
       private d3: D3;
    
       constructor(
          private d3Service: D3Service,    
       ) { 
          this.d3 = this.d3Service.getD3();    
          window["d3"] = this.d3Service.getD3(); // <-- here
       }
    
       initializeLasso() {
          lasso() // <-- no need to use this.d3 as a parameter
             .items(this.d3.selectAll(".myCircles"))
             .targetArea(this.d3.select(".backgroundRectangle"));
       }
    }
    

    选项 2

    只需破解 d3-lasso.js 代码即可获取 d3 对象。

    function lasso(d3) {...}
    

    然后在你的 ts 文件中调用它

        import { lasso } from 'd3-lasso';
    
        // ...
    
        initializeLasso() {
           lasso(this.d3) // <-- use this.d3 as a parameter
             .items(this.d3.selectAll(".myCircles"))
             .targetArea(this.d3.select(".backgroundRectangle"));
        }
    

    话虽如此,我正在研究另一个解决方案,因为每次我们调用 npm install 时,我都必须再次修复这个问题...

    【讨论】:

    • 选项一对我有用。一个完整的 plunkr 会非常棒:)
    猜你喜欢
    • 2017-01-19
    • 2016-12-15
    • 2017-05-08
    • 2016-07-31
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2023-03-16
    • 2018-04-18
    相关资源
    最近更新 更多