Posted on Mon Jun 19 2023
A generic method for displaying loading stats on Angular
Introduction
Sometimes, we require additional information about the user's request to provide them with a better user experience. One way to enhance their experience is by displaying a loader animation to indicate that their request is in progress. There are many ways to achieve that, a common approach is used and can be exemplified as follows:
Chart example
Code example
example.component.ts
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
})
export class ExampleComponent implements OnInit {
loading: boolean = false;
result: any[] = [];
constructor(private _exampleService: ExampleService) {}
ngOnInit() {
this.loadData();
}
loadData() {
this.loading = true;
this._exampleService.getExampleData().subscribe(
(response: any) => {
this.result = response;
this.loading = false;
},
(error: any) => {
console.log(error);
this.loading = false;
}
);
}
}
example.component.html
<main>
<div *ngIf="!loading" class="content">
<!-- handle data content -->
... content ...
</div>
<!-- loading indicator -->
<div *ngIf="loading">
loading ...
</div>
</main>
let's break this so we can understand what's happening here
loading: boolean = false;
result: any[] = [];
constructor(private _exampleService: ExampleService) {}
We declare two properties: one to store the data and another to track the loading state of the service we will be using. Additionally, we inject the ExampleService into our component.
ngOnInit() {
this.loadData();
}
loadData() {
this.loading = true;
this._exampleService.getExampleData().subscribe(
(response: any) => {
this.result = response;
this.loading = false;
},
(error: any) => {
console.log(error);
this.loading = false;
}
);
}
After initializing the app, we execute the loadData function, which sets the loading variable to true. We then subscribe to our service to retrieve the data, assuming that the service sends an HTTP request. We handle both success and error states, and finally set the loading variable to false.
using this approach is fine and give the exact same result, but we have to repeat the same steps in every component in our app, and set the loading state on each subscription. to keep track of all requests in our app we should use Interceptors