TypeError: Cannot read property 'city' of undefined
我的应用程序在浏览器中呈现得很好,但我在Chrome控制台中得到了这个错误,我希望了解/修复这个错误。控制台给出了3次错误,指向<span>{{current.city}}, {{current.country}} </span>
文件/行CurrentWeatherComponent.html:3
如果我删除{{current.city}},
,它会给出错误TypeError: Cannot read property 'country' of undefined
Thing is,在浏览器中,应用程序实际上呈现了current
城市,current
国家,current
日期,以及current
的所有其他属性。由于错误在控制台中打印了三次,但随后呈现良好,我猜这与时间有关?
下面的代码是完整的。让我知道如果(和什么)我需要张贴更多细节。
HTML:
current-weather.component.html:
<div>
<div>
<span>{{current.city}}, {{current.country}} </span>
<span>{{current.date | date:'fullDate'}}</span>
</div>
<div>
<img [src]='current.image'>
<span>{{current.temperature | number: '1.0-0'}}℉</span>
</div>
<div>
{{current.description}}
</div>
</div>
组件:
current-weather.component.ts
import { Component, OnInit } from '@angular/core'
import { ICurrentWeather } from '../interfaces'
import { WeatherService } from '../weather/weather.service'
@Component({
selector: 'app-current-weather',
templateUrl: './current-weather.component.html',
styleUrls: ['./current-weather.component.css'],
})
export class CurrentWeatherComponent implements OnInit {
current: ICurrentWeather
constructor(private weatherService: WeatherService) {}
ngOnInit() {
this.weatherService
.getCurrentWeather('Hilversum', 'NL')
.subscribe(data => (this.current = data))
}
}
发布于 2018-12-20 03:32:34
在weatherService.getCurrentWeather
函数发出data
之前,this.current
是undefined
,因此您可以在控制台中看到这些错误。
您可以使用{{current?.city}}
,并对current
的所有其他属性执行相同的操作。或者,通过使用*ngIf
属性,您可以等待呈现所有使用current
的元素,直到它可用:
<div *ngIf="current">
<div>
<span>{{current.city}}, {{current.country}} </span>
<span>{{current.date | date:'fullDate'}}</span>
</div>
<div>
<img [src]='current.image'>
<span>{{current.temperature | number: '1.0-0'}}℉</span>
</div>
<div>
{{current.description}}
</div>
</div>
https://stackoverflow.com/questions/53857932
复制相似问题