TypeError: Cannot read property of undefined - but site works accurately - Angular 7

TypeError: Cannot read property of undefined - but site works accurately - Angular 7

TypeError: Cannot read property 'city' of undefined

我的应用程序在浏览器中呈现良好,但我在 Chrome 控制台中收到此错误,我想 understand/fix。 控制台给出错误 3 次,指向 file/line CurrentWeatherComponent.html:3<span>{{current.city}}, {{current.country}} </span>

如果我删除 {{current.city}}, 它将给出错误 TypeError: Cannot read property 'country' of undefined 事实是,在浏览器中,应用程序实际上呈现了 current 城市、current 国家、current 日期和 current 的所有其他属性。 由于错误在控制台中打印了三次,但随后呈现得很好,我猜这与时间有关?

为了完整起见,下面是代码。让我知道我是否需要(以及什么)post 了解更多详情。

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

weatherService.getCurrentWeather 函数发出 data 之前,this.currentundefined,因此您会在控制台中看到这些错误。

您可以使用 {{current?.city}} 并对 current 的所有其他属性执行相同的操作。或者您可以等待渲染所有使用 current 的元素,直到它可用,方法是使用 *ngIf 属性:

<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>