- Angular 6 for Enterprise:Ready Web Applications
- Doguhan Uluca
- 181字
- 2021-06-25 21:20:39
Property initialization
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:
Results of Property Initialization
To make this view presentable to user, we will have to code for default values on every property on the template. So by fixing the null guarding issue by initialization, we created a default value handling issue. Both the initialization and the default value handling are O(n) scale tasks for developers. At its best, this strategy will be annoying to implement and at its worst, highly ineffective and error prone, requiring, at minimum, O(2n) effort per property.