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

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

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

我尝试过以下选项:

根组件:

  1. _router.events.subscribe((routerEvent: RouterEvent) => {
  2. if (routerEvent instanceof NavigationStart) {
  3. console.log("start");
  4. this.loading = true;
  5. } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
  6. console.log("end");
  7. this.loading = false;
  8. }
  9. });

根组件HTML:

加载图标根本不显示.

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

enter image description here

更新:

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

  1. public loading: boolean = true;
  2. console.log(routerEvent);
  3. console.log("Loading is " + this.loading);

enter image description here

更新2:

app.component.html:

app.component.ts:

  1. import {Component,OnInit,AfterViewInit} from '@angular/core';
  2. import {AuthenticationService} from "../../authentication/services/authentication.service";
  3. import {Router,Event,NavigationStart,NavigationEnd,NavigationCancel,NavigationError} from "@angular/router";
  4. import {RouterEvent} from "@angular/router";
  5. import UIkit from 'uikit'
  6. @Component({
  7. selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
  8. })
  9. export class AppComponent implements OnInit,AfterViewInit {
  10. isLoggedIn: boolean;
  11. public loading: boolean = true;
  12. UIkit: any;
  13. constructor(private _router: Router,private _authService: AuthenticationService) {
  14. _router.events.subscribe((routerEvent: RouterEvent) => {
  15. if (routerEvent instanceof NavigationStart) {
  16. this.loading = true;
  17. console.log(routerEvent);
  18. console.log("Loading is " + this.loading);
  19. } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
  20. this.loading = false;
  21. }
  22. });
  23. }
  24. ngAfterViewInit() {
  25. }
  26. ngOnInit() {
  27. UIkit.notification({
  28. message: 'my-message!',status: 'primary',pos: 'top-right',timeout: 5000
  29. });
  30. }
  31. }
最佳答案
这里的问题非常简单但容易错过.你不正确地检查路由器事件类型,它应该是这样的:

  1. 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相关文章