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

前端之家收集整理的这篇文章主要介绍了javascript – 如何从Angular 4中的NVD3回调导航组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经在Angular 4中实现了NVD3图表.在回调函数内写了一个Click事件,点击图表我试图导航到另一个组件,但我无法导航.

代码

  1. import { Router} from '@angular/router';
  2. export class MyNewComponentComponent implements OnInit {
  3. constructor(public router: Router)
  4. {
  5.  
  6. }
  7. this.options = {
  8. chart: {
  9. type: 'discreteBarChart',height: 450,margin : {
  10. top: 20,right: 20,bottom: 50,left: 55
  11. },x: function(d){return d.label;},y: function(d){return d.value;},showValues: true,valueFormat: function(d){
  12. return d3.format(',.4f')(d);
  13. },duration: 500,xAxis: {
  14. axisLabel: 'X Axis'
  15. },yAxis: {
  16. axisLabel: 'Y Axis',axisLabelDistance: -10
  17. },callback: function(chart){
  18. chart.discretebar.dispatch.on('elementClick',(angularEvent,e) => {
  19. console.log("Inside click");
  20. this.router.navigate(["/app-new-component2"]);
  21.  
  22.  
  23. });
  24.  
  25. }
  26.  
  27. }
  28. }

}

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

等待建议.提前致谢 ..

解决方法

所以你的问题就在这里
  1. callback: function(chart){ // note the callback function
  2. chart.discretebar.dispatch.on('elementClick',e) => {
  3. console.log("Inside click");
  4. this.router.navigate(["/app-new-component2"]);
  5. });
  6.  
  7. }

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

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

使用ES6(胖箭头)功能()=> {}将保留全局范围,以便您使用路由器.

猜你在找的JavaScript相关文章