2017-09-28 37 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));

相關問題