Angular 6 for Enterprise:Ready Web Applications
上QQ阅读APP看书,第一时间看更新

Safe navigation operator

Angular implements the safe navigation operation ?. to prevent unintended traversals of undefined objects. So, instead of writing initialization code and having to deal with template values, let's just update the template:

src/app/current-weather/current-weather.component.html
<p>
<p>
<span>{{current?.city}}, {{current?.country}}</span>
<span>{{current?.date | date:'fullDate'}}</span>
</p>
<p>
<img [src]='current?.image'>
<span>{{current?.temperature}}℉</span>
</p>
<p>
{{current?.description}}
</p>
</p>

This time, we didn't have to make up defaults, and we let Angular deal with displaying undefined bindings. You will note that just like the initialization fix, the errors have been reduced from 12 to 3. The app itself is in a somewhat better shape. There's no more confusing data being displayed; however, it still is not in a presentable state, as shown below:

Results of Safe Navigation Operator

You can probably imagine ways where the safe navigation operator can come in handy, in far more complicated scenarios. However, when deployed at scale, this type of coding still requires, at minimum, O(n) level of effort to implement.