2017-09-28 35 views
0

我有一个接口Weather。我正在尝试为组件内的接口创建一个对象数组。下面的代码是我的接口:Angular - 即使初始化后也无法读取未定义的属性'push'

export interface Weather { 
    city: String; 
    temp: String; 
    description: String; 
} 

现在我想创建我的组件内部对象的数组,这里是我的组件文件:

export class AppComponent { 
    title = 'Ng-Weather'; 
    weather: Weather[] = []; 
    constructor(private weatherService: WeatherService) { }  
    search(cityName) { 
    this.weatherService.getWeatherbyName(cityName) 
     .subscribe(this.storeData); 
    } 
    storeData(data: Weather) { 
    this.weather.push(data); 
    console.log('weather: ' + this.weather); 
    } 
} 

我我的控制台上得到的错误是: ERROR TypeError: Cannot read property 'push' of undefined

回答

1

...subscribe(this.storeData.bind(this))

,或者使用箭头功能

[更新]

所以,基本上,会发生什么是一个众所周知的this - 问题:在当你的subscription获得实际价值的那一刻,this没有指向组件了,但谁知道什么(如果没有什么特别的话,那么浏览器window对象)。因此,您需要做的是将this的范围转移(bind)到您提供给subscribe的功能,或者您需要使用所谓的箭头功能,因为它们不会创建新的范围;是这样的:

...subscribe(data => {console.log(data)})

+0

你能形容我为什么要这么做?由于我是初学者,需要了解更多。你也可以解释箭头功能吗? – JackSlayer94

+0

查看我的更新回答 –

0

您没有使用从订阅的返回数据。正如迪ZG说,你可以用一个箭头的功能是这样的:

this.weatherService.getWeatherbyName(cityName) .subscribe(data => this.storeData(data));

相关问题