网站搜索

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


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

代码 :

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"]); 


        });

      }

    }
  }

}

我在控制台中遇到此错误。无法找到用于重定向的组件引用。

等待建议。提前感谢..

答案#1

所以你的问题就在这里

  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,这将让你可以使用路由器。