In Angular, what is a robust way to display data in a view, taking into account loading-state and error-case?
Let's say we are getting a collection of documents from our backend and want to display those documents in our view using Angular. There are 3 states I want to take into account. For each of those states, I want to show a message to the user:
- Loading your data...
- Error trying to retrieve your data!
- Data retrieved successfully!
At the moment, I am doing the following. The issue I am facing is that both the "loading" and "error" messages are briefly displayed during the loading stage.
I am wondering how others go about solving this common use-case? Is it possible to do this by assigning different values to the myDocs variable, or do I have to introduce another variable?
TS
export class MyDocsComponent implements OnInit {
myDocs: IMyDoc | null;
ngOnInit() {
// get myDocs
this.myDocsService.getMyDocs()
// if success
.then( myDocs => { this.myDocs = myDocs; })
// if error: could not get myDocs from service
.catch( error => {
// what should go in here
// and how should this be checked in the view
// to display an error message to the user
// if the data could not be retrieved
// while also being able to display a loading message beforehand
// currently, I am doing:
this.myDocs = null;
// however, this leads to the error message
// incorrectly being displayed
// while loading the data
});
}
}
HTML
<!-- loading -->
<div class="loading" *ngIf="!myDocs">
Loading your data...
</div>
<!-- error -->
<div class="error" *ngIf="myDocs==null">
Error trying to retrieve your data!
</div>
<!-- success -->
<div class="success" *ngIf="myDocs">
Data retrieved successfully!
<div class="list" *ngFor="let d of myDocs">{{ d.title }}</div>
</div>