当我尝试从 API 调用获取响应并在模板中的响应对象中显示信息时,出现上述错误。
ERROR TypeError: Cannot read property 'list' of undefined.
在 service.ts 中,我正在进行服务器调用。我正在使用 OpenWeatherMap API。
getDetails(cityName, countryCd): Observable<any>{
return this.httpclient.get(`${this.url}${cityName},${countryCd}&APPID=${this.apiKey}`);
}
API返回的对象格式:
{"city":{"id":1851632,"name":"Shuzenji",
"coord":{"lon":138.933334,"lat":34.966671},
"country":"JP",
"cod":"200",
"message":0.0045,
"cnt":38,
"list":[{
"dt":1406106000,
"main":{
"temp":298.77,
"temp_min":298.77,
"temp_max":298.774,
"pressure":1005.93,
"sea_level":1018.18,
"grnd_level":1005.93,
"humidity":87,
"temp_kf":0.26},
"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
"clouds":{"all":88},
"wind":{"speed":5.71,"deg":229.501},
"sys":{"pod":"d"},
"dt_txt":"2014-07-23 09:00:00"}
]}
在 home.component.ts 中,我订阅了服务 API 调用。我得到的响应是“对象”类型。
我有一个名为城市的对象数组。我正在从服务器加载响应对象作为数组城市的每个对象中的属性之一。
this.cities = this.cityService.getCities().slice();
this.cities.forEach(element => {
this.weatherService.getDetails(element.cityName, element.countryCd).subscribe(response => {
element['cityWeather'] = response;});
});
在 home.component.html 中,我正在迭代此城市数组并使用来自 API 的响应数据。数据显示正常,没有任何问题。 但在控制台中,我看到城市数组的每次迭代都有错误 -
ERROR TypeError: Cannot read property 'list' of undefined.
<div class="col-md-4" *ngFor="let city of cities; let i = index">
<span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃</span>
<span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>
</div>
我对 Angular 比较陌生,需要知道这个错误是什么以及如何解决。
最佳答案
您的问题是在您引用的主页组件中
<span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃</span>
<span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>
这些值可能并非始终定义,因此如果 city.cityWeather
未定义,访问 .list
属性将导致错误
Cannot read property 'list' of undefined.
您可以使用 Angular 安全导航运算符(也称为 Elvis 运算符)来修复此问题。
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths
-- Angular docs
通过将 .
更改为 ?.
,Angular 在找不到对象的属性时不会抛出错误。
请注意,这仅适用于组件模板,不适用于 TypeScript 文件。
关于javascript - 错误类型错误 : Cannot read property 'list' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56312635/