在嵌套函数中设置变量值

时间:2017-12-14 10:55:17

标签: angular typescript

我试图访问typescript类中的变量。 添加checkLUCE1的第一个this可以轻松编辑。

第二个checkLUCE2在另一个函数中,我不知道如何为它设置新值:

export class ServiziConfigurazioneComponent implements OnInit {

constructor(private savelocal: SavelocaleService,
          private globals: GlobalsService) { }


checkLUCE1:boolean = false;
checkLUCE2:boolean = false;

handleFileSelect(evt,servizio,i){

    let target = evt.target || evt.srcElement || evt.currentTarget;
    let idAttr = target.attributes.id;
    let value = idAttr.nodeValue;
    let obj:any;

    document.getElementById(value+'-image').style.display="none";
    document.getElementById(value+'-loading').style.display = "block";

    let files = evt.target.files;
    let file = files[0];
    this.checkLUCE1 = true; //HERE I CAN SET THE VALUE

    if (files && file) {
        let reader = new FileReader();

        reader.onload = function() {
            (<HTMLImageElement>document.getElementById(value+'-image-file')).src  = reader.result;
            let binaryString = reader.result;
            let base64textString = btoa(binaryString);
            //console.log(base64textString);

            let obj = {};
            obj['file-'+servizio+'-'+i]= {
                'file' : base64textString
            };
            checkLUCE2= true; //HERE I CAN'T SET THE VALUE

            localStorage.setItem('currentUserLuceFile-'+i,base64textString);
        };
        reader.readAsDataURL(file);


        document.getElementById(value+'-image').style.display="block";
        document.getElementById(value+'-loading').style.display = "none";

        //this.savelocal.write('currentUserOfferta',JSON.stringify(obj));
    }
  }
}

2 个答案:

答案 0 :(得分:4)

您可以使用箭头功能来实现此功能。因此,您可以使用reader.onload = function() {...}而不是像reader.onload = () => {...}那样声明您的功能。看看this example

class Bla {

    // Your variables
    luce1: string = "sdfgsy";
    luce2: string = "sdfysd";

    // In your case that was "handleFileSelect"
    public doSomething() {
        alert(this.luce1);
        // this is what you are looking for. Inside the arrow function you can set the class level variable
        let anonymous = () => { this.luce2 = "Success" }

        anonymous();

        alert(this.luce2);
    }

}

let bla = new Bla();

bla.doSomething();

答案 1 :(得分:0)

有三种方法可以解决它:

将上下文存储在变量中:

var self=this;

document.onload=function () {
  self.myAttribute=...
};

使用箭头函数,其中上下文在声明时间而不是在执行时间中设置:

document.onload=() => {
  this.myAttribute=...
}

使用bind

将上下文绑定到函数
document.onload=(function () {
  this.myAttribute=...
}).bind(this);