在Angular2 Route Navigate上显示Load Spinner

时间:2016-07-28 13:01:04

标签: angular angular2-routing

我看过(this question)及其来自@borislemke的回答。

尽管如此,尝试使用Angular2 Demo Application,但在导航到另一条路线时不会改变Loader Div背景颜色。

我的AppComponent如下,

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

我的plunker是here进行实时测试。

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

感谢。

1 个答案:

答案 0 :(得分:0)

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

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

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

尝试上面的代码,您可以看到background-color正在发生变化。