首页 > 解决方案 > Angular 中的 d3.js 转换中断 - attrTween 调用错误的“this”

问题描述

我正在尝试使用 d3 v5 中最新的进入/更新/退出模式重新创建d3.js v5 圆环图的示例,并将转换作为 Angular 组件。一切看起来都很好,直到我使用示例数据中的数字并且过渡开始中断。我在 Stackblitz 上把它隔离了。您将看到正在发生的行为,但如果您将对象的第一个值更改oranges200,您会看到它工作得很好。我有点放大了原因,它似乎在 arcTween 函数中,它需要访问调用函数'this._current',但我认为它正在 Angular 组件中寻找它。

update(fruit) {
    this.svg
        .datum(this.data)
        .selectAll('path')
        .data(d3Shape.pie()
            .value((d: any) => d[fruit])
            .sort(null))
        .join(
            enter => enter
                .append('path')
                .text(d => d)
                .attr('fill', (d, i) => this.color(i))
                .attr('d', this.arc)
                .each(function (d) { this._current = d; }), // <--- This is the _current that I need access to 
            update => update
                .transition()
                .duration(2000)
                .attrTween('d', this.arcTween)
                .attr('fill', (d, i) => this.color(i))
                .attr('d', this.arc),
            exit => exit.remove()
    );
}


arcTween(a) {
  var i = d3Interpolate.interpolate(this._current, a); // It is assuming 'this' refers to a component level variable, should be the calling function scope
  this._current = i(0);
    return (t) => {
      return this.arc(i(t)); //  <-- this is referring correctly to the component arc variable
  };
}

标签: javascriptangulard3.jsthis

解决方案


推荐阅读