[英]how to instantiate the imported class in angular
我正在使用angualr天氣應用程序。 為此我創建了天氣課
export class Weather{
city: string;
condition: string;
icon: string;
temp: number;
}
我向天氣查詢發出http api請求。
我已經導入了這個Weather
類,並希望根據api調用中的json對象分配字段。
像這樣。
weather:Weather;
getWeather():void{
this.weatherserv.getWeather().subscribe(data=>{
this.weather.city=data.location.name;
this.weather.condition=data.condition.text;
this.weather.condition=data.condition.icon;
this.weather.temp=data.current.temp_c;
})
}
我得到的錯誤是:
Error: Cannot set property 'city' of undefined
你應該試試:
weather= new Weather();
或者根據您的情況,最好使用接口:
export interface Weather{
city?: string;
condition?: string;
icon?: string;
temp?: number;
}
weather:Weather = {};
在這里,我解釋了為什么在您的情況下使用接口更好。
嘗試這個:
weather: Weather = new Weather();
getWeather():void{
this.weatherserv.getWeather().subscribe(data=>{
this.weather.city=data.location.name;
this.weather.condition=data.condition.text;
this.weather.condition=data.condition.icon;
this.weather.temp=data.current.temp_c;
})
}
您應該從您的類中創建一個新對象,然后為其設置值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.