无法根据路由请求在 Angular 中显示微调器

Unable to show spinner in Angular on routing request

我正在尝试设置一个微调器来显示 angular 5 中的请求。到目前为止,我一直在使用此处找到的教程:

https://www.amadousall.com/angular-routing-how-to-display-a-loading-indicator-when-navigating-between-routes/

看起来很直接;根据事件设置一个布尔值以评估为 true 或 false。我真正需要对我的代码进行的唯一更改是 html 中的 ngx-spinner 而不是 mat-progress-bar。但是,到目前为止,我一直无法让微调器出现。

这是供参考的代码,尽管它与 link 的代码几乎相同:

import {Component} from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import {Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router} from '@angular/router';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    loading = false;

    constructor(private router: Router, private spinner: NgxSpinnerService) {
        this.router.events.subscribe((event: Event) => {
            console.log('Event Occured');
            switch (true) {
                case event instanceof NavigationStart: {
                    this.loading = true;
                    console.log(this.loading);
                    break;
                }
                case event instanceof NavigationEnd:
                case event instanceof NavigationError:
                case event instanceof NavigationCancel: {
                    this.loading = false;
                    console.log(this.loading);
                    break;
                }
                default: {
                    break;
                }
            }
        });
    }

    /*ngOnInit() {
        /!** spinner starts on init *!/
        this.spinner.show();

        setTimeout(() => {
            /!** spinner ends after 5 seconds *!/
            this.spinner.hide();
        }, 5000);
    }
*/

}

这里是 app.component.html:

<ngx-spinner [hidden]="loading==false"
             bdColor = "rgba(51, 51, 51, 0.8)"
             size = "default"
             color = "#ffee00"
             type = "pacman"
>
<app-nav></app-nav>
<router-outlet [hidden]="loading==true">
</router-outlet>

我希望微调器在 loading 为真时显示,而 router-outlet 及其提供的内容隐藏。一旦 loading 为假,微调器将被隐藏,内容将被显示。

到目前为止,我只能在注释掉除 NavigationStart 以外的所有情况时让微调器显示,从而防止 loading 永远变为 false。此外,我能够看到微调器后面的 router-outlet 返回的内容,尽管上面有隐藏标签。我可以通过将它放在 div:

中来隐藏它
<div [hidden]="loading==true">
    <app-nav></app-nav>
    <router-outlet>
    </router-outlet>
</div>

但这仍然不能解决这样一个事实,即当我允许 loading 求值为 false 时,我一开始就看不到微调器;它立即加载路由器插座返回的组件。我是 angular 的新手,所以这是 运行 的我。这仅仅是我看到微调器的加载速度变快的情况,还是其他原因在起作用?

你看不到微调器,因为它隐藏得非常快。将一些解析器附加到路由以查看微调器的运行情况。您的微调器可能会显示大约 100 毫秒。

尝试在此处设置超时以强制微调器显示

case event instanceof NavigationCancel: {
  console.log(this.loading);
  // force to wait 2 seconds to see the spinner.
  setTimeout(() => {
    this.loading = false;
  }, 2000);
  break;
}

正如 Karol 所提到的,它发生得太快了,否则无法看到微调器。没关系,您不需要等待来自远程服务器的东西。这一切在本地发生得相当快。