我试图将数据传递到在组件内部声明的数组,但是我只获得了数组的第一个索引,其他元素没有返回。
我读到程序异步工作,并且只获取第一个索引,而且他们建议在for循环中更改var i,让ı对其进行更改。
组件:
weathers: Weather[] = [{adress:'',city:''}];
weather: Weather;
constructor(private weatherService: WeatherService) {
}
ngOnInit() {
this.weatherService.getWeather().subscribe(weathers =>
{
let size = (Object).keys(weathers).length;
this.weathers = Weather[size] = [{adress:'',city:''}];
console.log(weathers);
console.log(size);
for(let i=0;i<size;i++) {
const adress = weathers[i].adress;
const city = weathers[i].city;
this.weathers[i].adress=adress;
this.weathers[i].city=city;
}
}
);
}
服务:
export class WeatherService {
weatherList: Weather[];
constructor(private http: HttpClient) { }
getWeather() {
return this.http.get<Weather>('/api/weathers');
}
}
班级:
export class Weather {
city: string;
adress: string;
}
ERROR TypeError:
Cannot set property 'adress' of undefined
at SafeSubscriber._next (weather.component.ts:31)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:185)
at SafeSubscriber.next (Subscriber.js:124)
答案 0 :(得分:0)
您不应该这样使用数组:this.weathers = Weather[size] = [{adress:'',city:''}];
。制作时无需设置数组的大小:
let size = (Object).keys(weathers).length;
this.weathers = [];
for(let i=0;i<size;i++) {
const adress = weathers[i].adress;
const city = weathers[i].city;
this.weathers.push({'adress': adress, 'city': city});
}
一种更好的方法是使用map
运算符
console.log(weathers);
this.weathers = (Object).keys(weathers).map(key => {
return {
adress: weathers[key].adress,
city: weathers[key].city
}
}