javascript - 如何从 Angular 4 中的 NVD3 回调导航组件?

标签 javascript angular nvd3.js angular4-router

我已经在 Angular 4 中实现了 NVD3 图表。在回调函数中编写了一个 on Click 事件,在单击图表时我试图导航到另一个组件,但我无法导航。

代码:

import { Router} from '@angular/router';
export class MyNewComponentComponent implements OnInit {
constructor(public router: Router)
  {

  }
 this.options = {
    chart: {
      type: 'discreteBarChart',
      height: 450,
      margin : {
        top: 20,
        right: 20,
        bottom: 50,
        left: 55
      },

      x: function(d){return d.label;},
      y: function(d){return d.value;},
      showValues: true,
      valueFormat: function(d){
        return d3.format(',.4f')(d);
      },
      duration: 500,
      xAxis: {
        axisLabel: 'X Axis'
      },
      yAxis: {
        axisLabel: 'Y Axis',
        axisLabelDistance: -10
      },
      callback: function(chart){ 
        chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
             console.log("Inside click"); 
                            this.router.navigate(["/app-new-component2"]); 


        });

      }

    }
  }

我在控制台中收到此错误。无法找到要重定向的组件引用。 enter image description here

等待建议。提前致谢..

最佳答案

所以你的问题就在这里

  callback: function(chart){ // note the callback function
    chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
         console.log("Inside click"); 
         this.router.navigate(["/app-new-component2"]); 
    });

  }

所以你的回调在哪里,你正在使用 es5 function() 这意味着该函数中的任何内容都不会保留全局范围 this 而是创建一个新范围.因此,在这种情况下,当您执行 this.router.navigate 时,您不引用组件(全局 this),而是引用函数作用域 this没有路由器。所以你想做的是这个,

  callback: (chart) => { 
    chart.discretebar.dispatch.on('elementClick', (angularEvent,e) => {
         console.log("Inside click"); 
         this.router.navigate(["/app-new-component2"]); 
    });

  }

使用 ES6(粗箭头)函数 () => {} 将保留全局作用域 this,这将允许您使用路由器。

关于javascript - 如何从 Angular 4 中的 NVD3 回调导航组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246237/

相关文章:

css - 在 Angular 5 的路由器导出中仅呈现组件模板

d3.js - 如何删除 nvd3.js 图中的小数点?

javascript - onload 在 wordpress 中不起作用

javascript - 试图让 XUI 工作

javascript - 如何在 Django 模板过滤器中用下划线替换逗号

angular - 在 Angular CLI 中使用 ng build --prod 时使用 cdn 而不是本地服务

node.js - 如何使用模块中的 Gulp : Error: Multiple anonymous System. 注册调用以 Angular 2 加载系统导入中的捆绑文件

css - 工具提示上的 NVD3 圆形边框

javascript - D3 在 stackedAreaChart 中乘以数据点

javascript - jQuery加载其他html页面,但如何恢复到原始内容