【问题标题】:Angular2 - Access component properties from method of propertiesAngular2 - 从属性方法访问组件属性
【发布时间】:2017-03-22 12:57:38
【问题描述】:

我正在尝试读取文件并将读取的内容存储在 Component 的私有变量中。到目前为止,我无法访问组件的属性,因为我得到 this 的推荐,因为 FileReader 而不是组件。

我的代码是这样的

private ReadTheFile(file:File) {

    var myReader: FileReader = new FileReader();
    myReader.readAsText(file);
    myReader.onloadend = function (e) {

        //Do something here with myReader.result

    }

    //Get the modified result here, and assign it to public property.

}

那么,如何在这样的方法中访问组件属性呢?哪个是FileReader 实例的方法,而不是组件。

【问题讨论】:

    标签: javascript angular typescript filereader typescript2.0


    【解决方案1】:

    不要在类中使用关键字function。正如您所注意到的,这将更改 this 上下文。使用箭头函数

    private ReadTheFile(file:File) {
    
        var myReader: FileReader = new FileReader();
        myReader.readAsText(file);
        myReader.onloadend = (e) => {
    
            //Do something here with myReader.result
    
        }
    
        //Get the modified result here, and assign it to public property.
    
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用arrow function 来保留组件上下文:

      myReader.onloadend = (e) => {
              //Do something here with myReader.result
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-11
        • 1970-01-01
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 2018-10-24
        • 1970-01-01
        相关资源
        最近更新 更多