Reputation: 3657
I've got a loading bar that is displayed on each HTTP request. This works perfectly for requests that take more than 300ms or so (such as API calls that fetch a lot of data), but looks silly when a request is short, the bar just flashes then vanishes and is rather distracting.
I'm trying to work out how I can hide the loading bar unless the time taken to return is longer than nms.
To control the loading bar I have a simple method on AppCompoent
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
loading: boolean = true;
constructor(private router: Router) {
router.events.subscribe((routerEvent: Event) => {
this.checkRouterEvent(routerEvent);
});
}
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
// sleep here for n ms perhaps?
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
}
}
Or is the already a standard pattern I've completely missed on how to handle this situation?
Upvotes: 0
Views: 73
Reputation: 7466
You can just add a new variable to account for a "finished loading" state.
Here is a solution: add a finishedLoading: boolean = true;
to your class. Then:
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
this.finishedLoading = false;
this.loading = false;
setTimeout(() => {
if (!this.finishedLoading) {
this.loading = true;
}
} , 300);
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.finishedLoading = true;
this.loading = false;
}
}
Upvotes: 1