错误TypeError:无法设置undefined的属性'property'

时间:2017-09-11 06:48:35

标签: angular

我的问题是在我执行订阅方法时创建的,我不明白为什么。 这是代码,并在控制台中生成错误:

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)

1 个答案:

答案 0 :(得分:1)

你的问题就在这里。您使用的i变量closure用于

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

表示它捕获i变量。

此代码有效asynchronously。表示在subscribe准备就绪后,此getNumberTotal将起作用。

当您的代码第一次运行时,i0。它到达此行并将此函数传递给另一个线程(不是Javascript线程)来运行并继续。当它完成调用时,它等待你的Javascript线程完成它的代码,之后你得到ithis.zones.length。事件循环得出订阅的回调,并看到变量i,其值为this.zones[this.zones.length],当它试图调用this.zones [this.zones [this.zones.length]]时,未定义。那么为什么你会收到错误。

将您的var i定义替换为let i。它会强制for loop为每次迭代创建自己的i变量,每个subscribe都会捕获它自己的i