Angular天气应用实例化导入类报错:无法设置未定义属性'city'
解决Angular中Cannot set property 'city' of undefined的问题
这个错误太常见啦——你只给weather变量声明了Weather类型,但从来没有创建这个类的实例,所以它初始值是undefined,当然没法给它的属性赋值啦!下面给你几种简单的解决办法:
方法1:声明变量时直接实例化
在定义weather变量的时候,就用new Weather()创建一个空实例:
weather: Weather = new Weather(); getWeather(): void { this.weatherserv.getWeather().subscribe(data => { this.weather.city = data.location.name; this.weather.condition = data.condition.text; // 注意!你原来的代码里这里重复赋值condition了,应该是icon哦 this.weather.icon = data.condition.icon; this.weather.temp = data.current.temp_c; }) }
这样一开始weather就不是undefined了,后续可以直接给属性赋值。
方法2:在回调中创建实例
如果不想提前创建空对象,可以在API请求返回数据后再实例化:
weather: Weather; getWeather(): void { this.weatherserv.getWeather().subscribe(data => { // 先创建实例,再赋值 this.weather = new Weather(); this.weather.city = data.location.name; this.weather.condition = data.condition.text; this.weather.icon = data.condition.icon; this.weather.temp = data.current.temp_c; }) }
方法3:用构造函数简化赋值(更优雅)
给你的Weather类添加一个带参数的构造函数,这样可以一步完成实例化和赋值:
export class Weather{ constructor( public city: string, public condition: string, public icon: string, public temp: number ){} }
然后在回调里直接传入参数创建实例:
weather: Weather; getWeather(): void { this.weatherserv.getWeather().subscribe(data => { this.weather = new Weather( data.location.name, data.condition.text, data.condition.icon, data.current.temp_c ); }) }
额外建议:如果只是数据结构,用接口更轻量
如果你的Weather类只是用来定义数据结构,没有任何方法或逻辑,换成interface会更合适(接口只是类型检查,不会生成实例对象,更轻量):
export interface Weather{ city: string; condition: string; icon: string; temp: number; }
然后直接赋值对象字面量:
weather: Weather; getWeather(): void { this.weatherserv.getWeather().subscribe(data => { this.weather = { city: data.location.name, condition: data.condition.text, icon: data.condition.icon, temp: data.current.temp_c }; }) }
最后别忘了修正你代码里的小bug:原来的代码中两次给condition赋值了,第二次应该是icon,不然你的图标数据会覆盖天气状况文本哦!
内容的提问来源于stack exchange,提问作者Kaleem Nalband
相关产品推荐
相关产品推荐

