Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - ERROR TypeError: Cannot set property 'abc' of undefined Angular2

I have a input type file HTML element and want to upload and read a JSON file and store the file's object content in a local variable. Suppose this is the JSON object I am getting after reading that file :-

{
   name:{
        firstName: "Name1",
        lastName: "Name2"
   }
}

Now, I want to store this object in a variable after reading the file,

private jsondata = {};

readfile(eve){
    let reader:any,
    target:EventTarget;
    reader= new FileReader();

    reader.onload = function(eve:any) {
        this.jsondata['json_def'] = JSON.parse(eve.target.result);

        console.log(this.json_def);
    }
    reader.readAsText(eve.target.files[0]);
}

This is the error I am receiving in console when I upload it:

ERROR TypeError: Cannot set property 'json_def' of undefined
at FileReader.reader.onload (create-model.component.ts:135)
at ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.es5.js:3890)
at ZoneDelegate.invoke (zone.js:390)
at Zone.runGuarded (zone.js:154)
at FileReader.<anonymous> (zone.js:132)

And I am not getting the exact reason of this error. Please someone help. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this in the reader.onload is not the object's context. So it haven't any variable with name jsondata. You can use arrow function to preserve your context to the object.

reader.onload = (eve:any) => {
    this.jsondata['json_def'] = JSON.parse(eve.target.result);

    console.log(this.json_def);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...