Angular2 - 从属性方法访问组件属性

Angular2 - Access component properties from method of properties

我正在尝试读取文件并将读取的内容存储在 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 实例的方法,而不是 Component.

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

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

    }

不要在 class 中使用关键字 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.

}