2017-12-14 18 views
0

typescriptクラス内の変数にアクセスしようとしています。 最初のcheckLUCE1thisを追加すると簡単に編集できます。ネストされた関数の変数値を設定します。

秒1 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)); 
    } 
    } 
} 

答えて

3

あなたはこれをachiveするために、矢印の機能を使用することができます。したがって、reader.onload = function() {...}のような関数を宣言する代わりに、reader.onload =() => {...}を使用することができます。 this exampleをご覧ください。

ストア変数のコンテキスト:

var self=this; 

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

使用矢印機能、コンテキストが宣言時に設定されている、いない実行時間でそれを解決するには、3つの方法があります

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(); 
+0

それは私にエラーをスロー http://prntscr.com/hnd9y6 –

+0

@SergioGandrusあなたが単語 'function'を省略することがあります!ただそれを削除します。 'reader.onload =()=> {...}' – indexoutofbounds

+0

パーフェクト!!最後に動作します! Thx –

0

:関数のコンテキストがを使用して

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

バインド0:

document.onload=(function() { 
    this.myAttribute=... 
}).bind(this); 
+0

ありがとう;) –

関連する問題