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

问题描述 投票:6回答:1

我已经在Angular 4中实现了NVD3图表。在回调函数内写了一个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

等待建议。提前致谢 ..

javascript angular nvd3.js angular4-router
1个回答
7
投票

所以你的问题就在这里

  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的函数范围router。所以你想要做的就是这个,

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

  }

使用ES6(胖箭头)功能() => {}将保留全局范围this,它将让你使用你的路由器。

© www.soinside.com 2019 - 2024. All rights reserved.