我的问题是在我执行订阅方法时创建的,我不明白为什么。 这是代码,并在控制台中生成错误:
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 :(得分:1)
你的问题就在这里。您使用的i
变量closure用于
.subscribe((data)=>{
this.zones[i].numero=data
})
表示它捕获i
变量。
此代码有效asynchronously
。表示在subscribe
准备就绪后,此getNumberTotal
将起作用。
当您的代码第一次运行时,i
为0
。它到达此行并将此函数传递给另一个线程(不是Javascript线程)来运行并继续。当它完成调用时,它等待你的Javascript线程完成它的代码,之后你得到i
值this.zones.length
。事件循环得出订阅的回调,并看到变量i
,其值为this.zones[this.zones.length]
,当它试图调用this.zones [this.zones [this.zones.length]]时,未定义。那么为什么你会收到错误。
将您的var i
定义替换为let i
。它会强制for loop
为每次迭代创建自己的i
变量,每个subscribe
都会捕获它自己的i
。