javascript – 在路线解析器/路线更改上显示加载图标

前端之家收集整理的这篇文章主要介绍了javascript – 在路线解析器/路线更改上显示加载图标前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图在路由解析器从数据库获取数据时显示加载图标.

我尝试过以下选项:

根组件:

_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;
  }

});

根组件HTML:

加载图标根本不显示.

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

enter image description here

更新:

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

 public loading: boolean = true;

 console.log(routerEvent);

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

enter image description here

更新2:

app.component.html:

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
  });

 }

}
最佳答案
这里的问题非常简单但容易错过.你不正确地检查路由器事件类型,它应该是这样的:

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

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

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

猜你在找的JavaScript相关文章