问题描述
我在每个页眉上都有图片和文字。有时图像加载缓慢,显示文本,1-2 秒后标题图像显示在应有的位置,这不是很好的用户体验。我如何才能显示我的 ngx-spinner,直到我的组件中的全部数据 - 在路由完成时加载?
我尝试过的 - 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();
}
}
}
应用组件 html
<ngx-spinner bdColor="rgba(51,51,0.8)" size="medium" color="#fff" type="ball-scale-multiple">
<p style="font-size: 20px; color: white">Loading...</p>
</ngx-spinner>
但它不起作用。当我的路线正在改变并且组件在那里呈现时,我没有得到 Spinenr
解决方法
尝试为此使用生命周期钩子。使用路由器事件我们无法定义组件是否完全加载。对于这种情况,您可以 ngAfterViewInit 生命周期。
检查以下网站作为参考