web-dev-qa-db-ja.com

Angular 2でルート間を移動するときにロード画面を表示する

Angular 2でルートを変更したときにロード画面を表示する方法を教えてください。

現在のAngularルーターはナビゲーションイベントを提供します。これらを購読して、それに応じてUIを変更することができます。ルーターのトランジションが失敗した場合にスピナーを止めるためにNavigationCancelNavigationErrorのような他のイベントを考慮することを忘れないでください。

app.component.ts - ルートコンポーネント

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'

@Component({})
export class AppComponent {

  // Sets initial value to true to show loading spinner on first load
  loading = true

  constructor(private router: Router) {
    router.events.subscribe((event: RouterEvent) => {
      this.navigationInterceptor(event)
    })
  }

  // Shows and hides the loading spinner during RouterEvent changes
  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.loading = true
    }
    if (event instanceof NavigationEnd) {
      this.loading = false
    }

    // Set loading state to false in both of the below events to hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this.loading = false
    }
    if (event instanceof NavigationError) {
      this.loading = false
    }
  }
}

app.component.html - あなたのルートビュー

<div class="loading-overlay" *ngIf="loading">
    <!-- show something fancy here, here with Angular 2 Material's loading bar or circle -->
    <md-progress-bar mode="indeterminate"></md-progress-bar>
</div>

パフォーマンスの改善された答え:パフォーマンスを気にする方が良い方法がありますが、もう少し手間がかかりますが、パフォーマンスの向上は余分な作業の価値があります。 。スピナーを条件付きで表示するために*ngIfを使う代わりに、AngularのNgZoneRendererを使ってスピナーのオン/オフを切り替えることができます。 *ngIfasyncパイプを使うのに比べて、アニメーションが滑らかになることがわかりました。

これは、いくつかの調整を加えた私の以前の回答と似ています。

app.component.ts - ルートコンポーネント

...
import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'
import {NgZone, Renderer, ElementRef, ViewChild} from '@angular/core'


@Component({})
export class AppComponent {

  // Instead of holding a boolean value for whether the spinner
  // should show or not, we store a reference to the spinner element,
  // see template snippet below this script
  @ViewChild('spinnerElement')
  spinnerElement: ElementRef

  constructor(private router: Router,
              private ngZone: NgZone,
              private renderer: Renderer) {
    router.events.subscribe((event: RouterEvent) => {
      this._navigationInterceptor(event)
    })
  }

  // Shows and hides the loading spinner during RouterEvent changes
  private _navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      // We wanna run this function outside of Angular's zone to
      // bypass change detection
      this.ngZone.runOutsideAngular(() => {
        // For simplicity we are going to turn opacity on / off
        // you could add/remove a class for more advanced styling
        // and enter/leave animation of the spinner
        this.renderer.setElementStyle(
          this.spinnerElement.nativeElement,
          'opacity',
          '1'
        )
      })
    }
    if (event instanceof NavigationEnd) {
      this._hideSpinner()
    }
    // Set loading state to false in both of the below events to
    // hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this._hideSpinner()
    }
    if (event instanceof NavigationError) {
      this._hideSpinner()
    }
  }

  private _hideSpinner(): void {
    // We wanna run this function outside of Angular's zone to
    // bypass change detection,
    this.ngZone.runOutsideAngular(() => {
      // For simplicity we are going to turn opacity on / off
      // you could add/remove a class for more advanced styling
      // and enter/leave animation of the spinner
      this.renderer.setElementStyle(
        this.spinnerElement.nativeElement,
        'opacity',
        '0'
      )
    })
  }
}

app.component.html - あなたのルートビュー

<div class="loading-overlay" #spinnerElement style="opacity: 0;">
    <!-- md-spinner is short for <md-progress-circle mode="indeterminate"></md-progress-circle> -->
    <md-spinner></md-spinner>
</div>
175
borislemke

UPDATE:3 新しいルーターにアップグレードしたので、CanDeactivate guardを使用すると @ borislemke のアプローチは機能しません。私は私の古いメソッドにie:この答えを下げています

UPDATE2 :新しいルーターのルーターイベントは有望そうで、 @ borislemke による 回答 スピナーの実装の主な側面について説明しますが、テストしていませんが、お勧めします。

UPDATE1:Old-Routerの時代に、router.subscribe()で通知されるイベントroute-changedが1つしかなかったときに書いた。また、以下のアプローチの過負荷を感じ、router.subscribe()のみを使用してそれを実行しようとしましたが、canceled navigationを検出する方法がなかったため、 backfired それで、私は長いアプローチ(二重作業)に戻らなければなりませんでした。


あなたがAngular2であなたの方法を知っているなら、これはあなたが必要とするものです


Boot.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';

bootstrap(MyApp, [SpinnerService]);

ルートコンポーネント-(MyApp)

import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
  selector: 'my-app',
  directives: [SpinnerComponent],
  template: `
     <spinner-component></spinner-component>
     <router-outlet></router-outlet>
   `
})
export class MyApp { }

Spinner-Component (Spinner-serviceにサブスクライブして、それに応じてactiveの値を変更します)

import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
  selector: 'spinner-component',
  'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
  public active: boolean;

  public constructor(spinner: SpinnerService) {
    spinner.status.subscribe((status: boolean) => {
      this.active = status;
    });
  }
}

Spinner-Service (このサービスをブートストラップします)

スピナーコンポーネントによってサブスクライブされるオブザーバブルを定義して、変更時にステータスを変更し、スピナーをアクティブ/非アクティブに設定する機能を定義します。

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';

@Injectable()
export class SpinnerService {
  public status: Subject<boolean> = new Subject();
  private _active: boolean = false;

  public get active(): boolean {
    return this._active;
  }

  public set active(v: boolean) {
    this._active = v;
    this.status.next(v);
  }

  public start(): void {
    this.active = true;
  }

  public stop(): void {
    this.active = false;
  }
}

他のすべてのルートのコンポーネント

(サンプル):

import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
   template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {

  constructor(public spinner: SpinnerService){} 

  ngOnInit(){
    this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
  }

  ngOnDestroy(){
    this.spinner.start();
  }
}
38
Ankit Singh

単純なcssを使用しないのはなぜでしょうか。

<router-outlet></router-outlet>
<div class="loading"></div>

そしてあなたのスタイルでは:

div.loading{
    height: 100px;
    background-color: red;
    display: none;
}
router-outlet + div.loading{
    display: block;
}

あるいは、最初の答えとしてこれを実行することもできます。

<router-outlet></router-outlet>
<spinner-component></spinner-component>

そしてそれだけで

spinner-component{
   display:none;
}
router-outlet + spinner-component{
    display: block;
}

ここでのトリックは、新しいルートとコンポーネントが常にrouter-exitの後に表示されるため、単純なcssセレクタを使用して、ロードを表示および非表示にすることができます。

10
Milad

最初のルートだけに特別なロジックが必要な場合は、次のことができます。

AppComponent

    loaded = false;

    constructor(private router: Router....) {
       router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
                    .subscribe((e) => {
                       this.loaded = true;
                       alert('loaded - this fires only once');
                   });

ページフッターを非表示にする必要がありました。そうでなければページの上部に表示されていました。あなたが最初のページのためのローダーだけが欲しいならば、あなたはこれを使うことができます。

2
Simon_Weaver

この 既存の解決策 を使うこともできます。デモ はこちら です。 YouTubeローディングバーのように見えます。私はそれを見つけて私のプロジェクトに追加しました。

0
walkerbox