简体   繁体   中英

how to instantiate the imported class in angular

i am working on a angualr weather app. for which i have created weather class

 export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

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 i am getting is:

Error: Cannot set property 'city' of undefined

you should try:

weather= new Weather();

or in your case, it's better to use interfaces:

 export interface Weather{
          city?: string;
          condition?: string;
          icon?: string;
          temp?: number;
        }
weather:Weather = {};

here i explained why it's better to use interfaces in your case.

try this:

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;
           })
         }

您应该从您的类中创建一个新对象,然后为其设置值。

Test follow code:

weather: Weather = new Weather;

Here: the stackblitz for it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM