2017-05-30 11 views
0

こんにちは私は、私はいくつかのアドバイスを得ることができたと思っていたスコープに関連すると思うエラーに実行している人。私は配列を持っているので、結果をプッシュしたいと思っています。 私は試してみて結果をパブリックmyArray:Arrayにthis.test.forEach内からプッシュすると、次のエラーが型voidに存在しません。アドバイスをいただければ幸いです。foreachメソッド内で配列を更新する角度

export class componentName implements OnInit { 
public myArray:Array<any>; 

ngOnInit() { 
    this.test = diff(this.example1, this.example2); 

    this.test.forEach(function(part){ 
    let span = document.createElement('span'); 
    span.appendChild(document.createTextNode(part.value)); 

    this.myArray.push(span); // error does not exist on type void 
    }); 
} 
+3

可能性のある重複した[コールバックの内側に正しい\ 'この\'コンテキストにアクセスするには?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this -context-inside-a-callback) – echonax

答えて

3

最初のエラーは、thisに間違った範囲を使用していることです。

this.test.forEach(function(part){ 

this.test.forEach((part)=>{ 

する必要があり、あなたはあなたの配列を初期化する必要があります。

public myArray:Array<any> = []; 
関連する問題