2017-09-11 20 views
0

私はメソッドsubscribeを実行すると私の問題が作成され、なぜ私は理解しません。 これは、コードとエラーコンソールで発生している:エラーTypeError:未定義のプロパティ 'property'を設定できません

getInfo(idgestore:number){ 
    let zonaObs=this._zonaservice.getInfoParks(idgestore); 
    zonaObs.subscribe(data=>{ 
     this.zones=data; 
     var citta:string; 
     for(var i=0;i<this.zones.length;i++){ 
     // this.zones[i].citta=null; 
     this.location.lat=this.zones[i].latitudine; 
     this.location.lng=this.zones[i].longitudine; 
     this._zonaservice.getCity(this.location) 
     .subscribe((data)=>{ 
      citta=data; 
      }) 
     console.log(this.zones[i].id); 
     var id_zona=this.zones[i].id; 
     console.log(id_zona) 
     this._tipologiazonaservice.getnumberTotal(id_zona) 
     .subscribe((data)=>{ 
      this.zones[i].numero=data 
     }) 
     console.log(this.zones) 
     } 
    }); 

    } 

エラー:

ERROR TypeError: Cannot set property 'numero' of undefined 
    at SafeSubscriber._next (allinfopark.component.ts:44) 
    at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238) 
    at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185) 
    at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125) 
    at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89) 
    at CatchSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125) 
    at CatchSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89) 
    at MapSubscriber.webpackJsonp.../../../../rxjs/operator/map.js.MapSubscriber._next (map.js:83) 
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89) 
    at XMLHttpRequest.onLoad (http.es5.js:1226) 
+0

サービスコードも共有できますか?ここには「プロパティ」プロパティはありません。 – trichetriche

答えて

1

あなたの問題はここにあります。あなたは

.subscribe((data)=>{ 
    this.zones[i].numero=data 
}) 

ためclosureであることがi変数をキャプチャすることを意味同じi変数を使用しています。

このコードはasynchronouslyで動作します。このsubscribeが動作することを意味します。getNumberTotalが準備完了です。

コードが初めて実行されるとき、i0です。この行に達し、この関数を実行するために別のスレッド(Javascriptスレッドではない)に渡します。呼び出しが終了すると、Javascriptスレッドがコードを終了するまで待ちます。その後、iの値はthis.zones.lengthになります。イベントループはサブスクライバのコールバックを取得し、値this.zones[this.zones.length]の変数iを参照し、this.zones [this.zones [this.zones.length]]をコールしようとすると、未定義です。だからなぜあなたはエラーを取得します。

var iの定義をlet iに置き換えてください。それぞれの反復に対してfor loopがそれ自身のi変数を作成するように強制すると、それぞれsubscribeにはそれ自身のキャプチャがありますi

+0

ありがとうSuren、私はあなたの提案に従って、私は問題を解決しました。 –

関連する問題