如何将路线更改为功能?

How can I change my route into a function?

我有一个 angular 组件,其中我有一个函数与另一个函数。

我只想在单击函数中绘制的按钮时更改页面。我无法访问组件构造函数中声明的路由器。那么有人知道怎么做吗?

这是我的组件代码:

export class EncoursComponent{



  constructor(private serviceData : DataService, private router : Router) {
  }


  }

  //Fonction qui permet de dessiner les lignes et les points
  draw(id: any, events: any, options: any) {


    //Ici on définit les points
    svg.selectAll("circle")



      //I want that when I click, be redirected no another page
      .on("click", function(d: any) {
        var data : DataService = new DataService();

        //This line doesn't work
        var rout : Router = new Router();

        //I can't acces to this.router
        this.router.navigate("/affecter");


      });
  }

因为function有自己的作用域。您可以将 function 更改为箭头函数,如下所示


    svg.selectAll("circle")



      //I want that when I click, be redirected no another page
      .on("click", (d: any) => {
        var data : DataService = new DataService();

        //This line doesn't work
        var rout : Router = new Router();

        //I can't acces to this.router
        this.router.navigate("/affecter");


      });

你可以像那样将你的路由器注入到你的组件中

constructor (private router: Router) {}

接下来我会将您的内部函数更改为 arrow function 以获得 class(您的组件)的 this 范围。 现在您可以使用 this.router.navigate('/path')

导航