【问题标题】:How to navigate the component from NVD3 Callback in Angular 4?如何从 Angular 4 中的 NVD3 回调导航组件?
【发布时间】:2019-02-14 04:56:57
【问题描述】:

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


        });

      }

    }
  }

}

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

等待建议。提前谢谢..

【问题讨论】:

    标签: javascript angular nvd3.js angular4-router


    【解决方案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),您指的是没有router 的功能范围this。所以你想做的就是这个,

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2018-09-26
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多