Если у каждого компонента есть собственный маршрут, вы можете подписаться на Маршрутизатор.
В app.component.ts
import { Router, Event as RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
constructor(private router: Router) {
this.router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event)
});
}
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.loading = true
}
if (event instanceof NavigationEnd) {
this.loading = false
}
// 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
}
if (event instanceof NavigationError) {
this.loading = false
}
}
В app.component.html
<router-outlet></router-outlet>
<spinner-component [spinnerShow]="loading_data"></spinner-component>
Spinner.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'spinner-component',
templateUrl: './spinner.component.html',
styleUrls: ["./spinner.component.scss"]
})
export class SpinnerComponent {
@Input() spinnerShow: boolean;
}
Spinner.component.html
<div *ngIf="spinnerShow" class="sc-background"></div>
<div *ngIf="spinnerShow" [ngClass]="{'sc-default-spinner' : ref.children.length == 0 }" class="logo sc-center">
<div #ref><ng-content></ng-content></div></div>
Spinner.component.scss
.sc-background{
content : "";
z-index: 1004;
position: absolute;
top:-10%;
right:0;
left:0;
bottom: 0;
background-color: rgba(255,255,255,0.8);
}
.logo {
background: url("./../../../../assets/images/sprite/template.png") 0px 0px;
width:30px;
}
.sc-center{
top: 50vh;
margin: auto;
position: fixed;
left: 0;
right: 0;
z-index: 1005;
}