angular - d3v4 + Typescript + angular2 错误使用 d3.line().x((d) => {function})

标签 angular d3.js typescript

所以我有这个...

import { D3Service, D3, Selection } from 'd3-ng2-service';

interface ChartData {
    q: number,
    p: number
} 

export class GraphComponent implements OnInit{
   private d3;
   private x1;
   private y;

    constructor(element: ElementRef, d3Service: D3Service) { 
        this.d3 = d3Service.getD3(); 
        let d3 = this.d3;


    this.y = d3.scaleLinear()
    .domain([0,100])
    .range([330, 20])
    ;
    this.x1 = d3.scaleLinear()
    .range([0, 100])
    ;
}

   render() {
      let y = this.y;
      let x1 = this.x1;
      let data = [{p:1,q:1}, {p:0.5,q:2}]

       var line = d3.line()
          .x((d: ChartData) => {return x1(d.q);})
          .y((d: ChartData) => {return y(d.p);});

        svg.append("path")
          .data(data)
          .attr("class", "line")
          .attr("d", line);
   }
}

我在 .x(d: ChartData) 行上收到一条错误消息:

Argument of type '(d: ChartData) => any' is not assignable to parameter of type '(d: [number, number], index: number, data: [number, number][]) => number'. Types of parameters 'd' and 'd' are incompatible. Type '[number, number]' is not assignable to type 'ChartData'. Property 'q' is missing in type '[number, number]'.

然后我查看了 d3 的文档,其中说我需要通过 line(data) 将我的数据注入(inject) line() 以获得自定义数据。

var line = d3.line(data)
    .x((d: ChartData) => {return x1(d.q);})
    .y((d: ChartData) => {return y(d.p);});

然后导致这个错误...

ERROR in [default] file.ts:259:13 Supplied parameters do not match any signature of call target.

...尽管 d3 文档说我应该能够这样做。那我做错了什么?

最佳答案

你的第一个语法(没有传递data)是正确的。我认为您只需告诉 TypeScript 您要传递给 d3.line 的内容,例如:

var line = d3.line<ChartData>()
  .x((d: ChartData) => {return x1(d.q);})
  .y((d: ChartData) => {return y(d.p);});

它正在尝试使用默认值进行编译:

d3.line<[number, number]>

关于angular - d3v4 + Typescript + angular2 错误使用 d3.line().x((d) => {function}),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308115/

相关文章:

javascript - d3-tip 不适用于 webpack

javascript - 将 Json 数据加载到 nvd3 图中

javascript - 无法读取未定义的给定属性

typescript - ionic : How do I hide an element on load

javascript - 使用 Typescript 自定义光标

Angular CLI (7.0.5) 用于开发和生产的不同 Assets ?

angular - 将 gRPC 与 Electron 14 结合使用

svg - 如何使用 D3.js 在 SVG 中创建流布局?

arrays - Array.Reduce 上的类型错误

css - PrimeNG 选项卡 View 中选项卡面板标题的内联样式