In my particular case I am using Angular and Firebase Firestore, however, the question might also be relevant to Typescript and pure Javascript.
My application is solely depending on data I am fetching from Firestore. A minimum, reproducible example of code I would produce looks like this.
TS:
export class EditStudentComponent implements OnInit {
user:Object = {};
ngOnInit() {
this.NgProgress.start()
this.fb.user$.subscribe(user => {
this.user = user;
})
}
}
HTML:
User-Info:
Name: {{ user.name }}<br>
Age: {{ user.age }}<br>
In this scenario, a non existing property name
or age
would throw an error.
Is there a better way than doing something like this for every property?
export class EditStudentComponent implements OnInit {
user:Object = {};
ngOnInit() {
this.NgProgress.start()
this.fb.user$.subscribe(user => {
this.user = user;
//Setting default values for all properties individually
this.user.name = 'name' in this.user ? (this.user as any).name : 'No value found';
this.user.age = 'age' in this.user ? (this.user as any).age : 'No value found';
})
}
}
Age: {{ user?.age }}
– Sundeep Nov 17 '19 at 15:14