本文介绍了在Angular2路线上显示“负载微调器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了(这个问题)及其来自@borislemke的答案.

I have seen (this question) and its Answer from @borislemke.

实际上,尝试在Angular2演示应用程序上运行,但在导航到另一条路线时,它没有更改Loader Div Background的颜色.

Actaully, tried on Angular2 Demo Application but its not changing Loader Div Background color while Navigating to another route.

我的AppComponent如下,

My AppComponent is as follows,

import { Component, OnInit }          from '@angular/core';
import { Router, ROUTER_DIRECTIVES, NavigationStart, NavigationEnd, NavigationError, NavigationCancel } from '@angular/router';
import {NgClass} from '@angular/common';

import { DialogService }  from './dialog.service';
import { HeroService }    from './heroes/hero.service';

@Component({
  selector: 'my-app',
  template: `
    <h1 class="title">Component Router</h1>
    <div>Is Navigating -->  {{isLoading}}</div>

    <div [ngClass]="{afterLoad: !isLoading, loading: isLoading }" > Loader Spinner Container </div>

    <nav>
      <a routerLink="/crisis-center" routerLinkActive="active"
         routerLinkActiveOptions="{ exact: true }">Crisis Center</a>
      <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
      <a routerLink="/crisis-center/admin" routerLinkActive="active">Crisis Admin</a>
      <a routerLink="/login" routerLinkActive="active">Login</a>
    </nav>
    <router-outlet></router-outlet>
  `,
  styles:[`
    .loading{
    background-color:red
    }

    .afterLoad{
    background-color:yellow
    }
  `],
  providers:  [
    HeroService,
    DialogService
  ],
  directives: [ROUTER_DIRECTIVES, NgClass]
})
export class AppComponent implements OnInit {
    isLoading: boolean = false;

   constructor(private _router:Router) {}

    ngOnInit() {
        // TODO: assign proper type to event
        this._router.events.subscribe((event: any): void => {
            this.navigationInterceptor(event);
        });
    }

    navigationInterceptor(event): void {
        if (event instanceof NavigationStart) {
            this.isLoading = true;
        }
        if (event instanceof NavigationEnd) {
            this.isLoading = false;
        }
        if (event instanceof NavigationCancel) {
            this.isLoading = false;
        }
        if (event instanceof NavigationError) {
            this.isLoading = false;
        }
    }
}

我的监听器是此处用于实时测试.

My plunker is here for live test.

任何人都可以帮助我找出可能的失败原因吗?

Can anyone help me figuring out the possible cause of failure?

谢谢.

推荐答案

您的应用太快,无法获取导航更改:)

Your app is too fast to pick up the navigation changes :)

我添加了setTimeout来模拟慢速连接,如下所示:

I added a setTimeout to simulate a slow connection like so:

if (event instanceof NavigationEnd) {
    // this.isLoading = false;
    setTimeout(() => this.isLoading = false, 1000);
}

尝试上面的代码,您会看到background-color发生变化.

Try the above code and you can see the background-color changing.

这篇关于在Angular2路线上显示“负载微调器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:00