Как отобразить экран загрузки при маршрутизации с помощью навигации в Angular2?
Я пробовал это решение, но не смог заставить его работать. Я совершенно новичок в Angular2 (без знания AngularJS). Ну, экран загрузки не появляется, я думаю, мне нужно добавить некоторое время, чтобы оно отображалось, но где и как я не знаю.
app.component.ts
import {Component} from '@angular/core';
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: ['./loadingCSS.css']
})
export class AppComponent {
// Sets initial value to true to show loading spinner on first load
loading = true;
constructor(private router: Router) {
router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event);
});
}
// Shows and hides the loading spinner during RouterEvent changes
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
<a [routerLink]="['/ArrayOP']"><button>Array operation</button></a>
<a [routerLink]="['/Calci']"><button>Calculator</button></a>
<div class="loading-overlay" *ngIf="loading">
Loading<span class="d">.</span><span class="d d-2">.</span><span class="d d-3">.</span>
</div>
<router-outlet></router-outlet>
Я хочу добиться, чтобы экран загрузки отображался в каждой маршрутизации во всем приложении, и экран загрузки, который я пытаюсь показать, - это (ссылка на код). Любое предложение будет очень полезно.
1 ответ
Я нашел решение. Размещать это, если кому-то нужно это в будущем.
Это то, что я сделал... я добавил setTimeout
функциональность для app.component.ts как
import {
Component
} from '@angular/core';
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: ['./loadingCSS.css']
})
export class AppComponent {
// Sets initial value to true to show loading spinner on first load
loading = true;
constructor(private router: Router) {
router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event);
});
}
// Shows and hides the loading spinner during RouterEvent changes
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.loading = true;
}
if (event instanceof NavigationEnd) {
setTimeout(() => { // here
this.loading = false;
}, 2000);
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
setTimeout(() => { // here
this.loading = false;
}, 2000);
}
if (event instanceof NavigationError) {
setTimeout(() => { // here
this.loading = false;
}, 2000);
}
}
И изменил HTML как
<div class="loading-overlay" *ngIf="loading">
Loading<span class="d">.</span><span class="d d-2">.</span><span class="d d-3">.</span>
</div>
<div *ngIf="!loading">
<router-outlet></router-outlet>
</div>
Установленный тайм-аут будет работать, но это неправильный способ работы, поскольку он все равно будет показывать задержку данных, если она есть при переключении с одного маршрута на другой. Для лучших результатов не используйте установленный тайм-аут