Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在angular中实例化导入的类_Angular_Api - Fatal编程技术网

如何在angular中实例化导入的类

如何在angular中实例化导入的类,angular,api,Angular,Api,我正在开发angualr天气应用程序。 为此我创建了天气课 export class Weather{ city: string; condition: string; icon: string; temp: number; } 我向http api请求天气详情 我已经导入了这个Weather类,并希望根据api调用中的json对象分配字段 像这样 weather:Weather; getWeat

我正在开发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;
           })
         }
测试代码:

weather: Weather = new Weather;

这里:

这应该是公认的答案+1对于使用接口而不是类是的,我认为最好在这里使用接口而不是类,我认为这应该是公认的答案。