How can we effectively display data in an Angular view, considering loading state and error handling?
Imagine we are fetching a set of documents from our backend and need to present them in an Angular view. We want to address three possible scenarios by providing corresponding messages to the user:
- Loading your data...
- Error trying to retrieve your data!
- Data retrieved successfully!
Currently, my approach involves displaying both the "loading" and "error" messages briefly during the data retrieval process.
I am curious about how others tackle this common scenario. Is it feasible to manage this by manipulating the myDocs
variable, or should I introduce another variable for better control?
Typescript Implementation (TS)
export class MyDocsComponent implements OnInit {
myDocs: IMyDoc | null;
ngOnInit() {
// fetch myDocs
this.myDocsService.getMyDocs()
// if successful
.then( myDocs => { this.myDocs = myDocs; })
// if there's an error while retrieving myDocs from the service
.catch( error => {
// What actions should be taken here?
// How can this be managed in the view
// to inform the user that data retrieval failed?
// And also display a loading message prior to this.
// Currently, I am using:
this.myDocs = null;
// However, this results in the error message
// being displayed prematurely during data loading.
});
}
}
HTML Markup (HTML)
<!-- Loading State -->
<div class="loading" *ngIf="!myDocs">
Loading your data...
</div>
<!-- Error State -->
<div class="error" *ngIf="myDocs==null">
Error trying to retrieve your data!
</div>
<!-- Success State -->
<div class="success" *ngIf="myDocs">
Data retrieved successfully!
<div class="list" *ngFor="let d of myDocs">{{ d.title }}</div>
</div>