在路线解析器/路线更改上显示装载图标

Sky*_*ker 5 javascript typescript angular angular5

我试图显示一个加载图标,而我route resolver从数据库中获取数据.

我尝试过以下选项:

根组件:

_router.events.subscribe((routerEvent: RouterEvent) => {

   if (routerEvent instanceof NavigationStart) {
      console.log("start");
      this.loading = true;

   } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
    console.log("end");
    this.loading = false;
  }

});
Run Code Online (Sandbox Code Playgroud)

根组件HTML:

<h1 *ngIf="loading">Loading</h1>
Run Code Online (Sandbox Code Playgroud)

加载图标根本不显示.

每次路由更改时,控制台日志中都会显示以下内容:

在此输入图像描述

更新:

以下是应用以下更改后的输出:

 public loading: boolean = true;

 console.log(routerEvent);

 console.log("Loading is " + this.loading);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新2:

app.component.html:

<div class="uk-offcanvas-content">
  <h1>{{loading}}</h1>
  <h1 *ngIf="loading">Loading</h1>

  <app-root-nav></app-root-nav>

  <app-notifications></app-notifications>

  <router-outlet></router-outlet> 
</div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

import {Component, OnInit, AfterViewInit} from '@angular/core';
import {AuthenticationService} from "../../authentication/services/authentication.service";
import {Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError} from "@angular/router";

import {RouterEvent} from "@angular/router";
import UIkit from 'uikit'

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
 })

 export class AppComponent implements OnInit, AfterViewInit {

  isLoggedIn: boolean;
  public loading: boolean = true;
  UIkit: any;

  constructor(private _router: Router, private _authService: AuthenticationService) {

  _router.events.subscribe((routerEvent: RouterEvent) => {
    if (routerEvent instanceof NavigationStart) {

      this.loading = true;
      console.log(routerEvent);
      console.log("Loading is " + this.loading);

  } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {

    this.loading = false;
  }
});
}

ngAfterViewInit() {
}

ngOnInit() {

  UIkit.notification({
    message: 'my-message!',
    status: 'primary',
    pos: 'top-right',
    timeout: 5000
  });

 }

}
Run Code Online (Sandbox Code Playgroud)

bry*_*n60 4

这里的问题非常简单,但很容易被忽略。您不正确地检查路由器事件类型,它应该是这样的:

else if (routerEvent instanceof NavigationError || routerEvent instanceof NavigationCancel || routerEvent instanceof NavigationEnd)
Run Code Online (Sandbox Code Playgroud)

你的方式总是返回 true ,因为你的第二个子句基本上是“或者如果 NavigationCancel 是 true ”,根据定义,它是一个现有类型。因此,当路由解析开始时,加载会立即设置为 false,因为在 NavigationEnd 事件之前有很多中间路由器事件,并且由于您检查的方式,所有这些事件都设置为 false。

plunk:https://plnkr.co/edit/7UKVqKlRY0EPXNkx0qxH ?p=preview