【问题标题】:How can I change my route into a function?如何将我的路线更改为函数?
【发布时间】:2019-07-18 07:15:03
【问题描述】:

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

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

这是我的组件的代码:

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


      });
  }

【问题讨论】:

    标签: angular typescript routing


    【解决方案1】:

    这是因为functions 有自己的作用域。您可以将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");
    
    
          });
    

    【讨论】:

      【解决方案2】:

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

      constructor (private router: Router) {}
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-30
        • 2022-10-18
        • 2020-01-31
        • 2020-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多