In JavaScript, the undefined
and null
values are a persistent issue that must be proactively dealt with every step of the way. There are multiple ways to guard against null
values in Angular:
- Property Initialization
- Safe Navigation Operator
?.
- Null Guarding with
*ngIf
In statically-typed languages such as Java, it is drilled into you that proper variable initialization/instantiation is the key to error free operation. So let's try that in CurrentWeatherComponent
by initializing current with default values:
src/app/current-weather/current-weather.component.ts
constructor(private weatherService: WeatherService) {
this.current = {
city: '',
country: '',
date: 0,
image: '',
temperature: 0,
description: '',
}
}
The outcome of these changes will reduce console errors from 12 to 3, at which point you will only be seeing API call related errors. However, the app itself will not be in a presentable state, as you can see below:
...