Reputation: 13
I have on every page header - image and text. Somoetimes the images are loading slow, the text is showed and after 1-2 seconds the heeader image shows up where it should which is not good user experience. How can i show my ngx-spinner until whole data in my component - loaded as route is comleted?
what i tried - app.component.ts
import { Component } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import {
Router,
// import as RouterEvent to avoid confusion with the DOM Event
Event as RouterEvent,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError
} from '@angular/router'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-app';
loading = true;
constructor(private spinner: NgxSpinnerService, private router: Router) {
this.router.events.subscribe((e: RouterEvent) => {
this.navigationInterceptor(e);
})
}
ngOnInit() {
}
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.loading = true;
this.spinner.show();
console.log(1111);
}
if (event instanceof NavigationEnd) {
this.loading = false;
this.spinner.hide();
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this.loading = false;
this.spinner.hide();
}
if (event instanceof NavigationError) {
this.loading = false;
this.spinner.hide();
}
}
}
app component html
<ngx-spinner bdColor="rgba(51,51,51,0.8)" size="medium" color="#fff" type="ball-scale-multiple">
<p style="font-size: 20px; color: white">Loading...</p>
</ngx-spinner>
but it is not working. I don't get the spinenr while my routes are chaning and while the compoenent is rendered there
Upvotes: 0
Views: 3249
Reputation: 1536
Try using lifecycle hooks for this. with the use of router events we can't define component is fully loaded or not. for this situation you can ngAfterViewInit life cycle.
Check the following site as reference
https://angular.io/guide/lifecycle-hooks
Upvotes: -1