Angular2 使用加载栏更改路线

Angular2 Changing routes with loading bar

我正在寻找最佳实践。当我改变路线时,我想要一个正在加载的 gif。所以我创建了一个服务

import { Injectable } from '@angular/core';

@Injectable()
export class LoadingService {

public active = false;

constructor() { }

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

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

}

和一个组件

import { Component } from '@angular/core';
import { LoadingService } from '../_services/index';

@Component({
selector: 'my-loading-component',
template: `<div *ngIf="loading.active" id="loadingDiv"></div>`,
styles: [`
#loadingDiv{
    background-color: black;
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 10000;
    background-image: url('ring.svg');
    background-position: center center;
    background-repeat: no-repeat;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}
`]
})
export class LoadingComponent {

constructor(public loading: LoadingService) {
   this.loading.active = true;
}

}

所以我将此服务注入组件以及 ngOnInit 和 ngOnDestroy

ngOnInit() {
  this.loading.stop();
}

ngOnDestroy() {
  this.loading.start();
}

你有任何其他建议吗... "one time code" 而不是每个组件..?

在您的根应用程序组件中,您可以订阅路由器事件,如下所示:-

this.router.events
        .subscribe((data: any) => {
            if (data instanceof NavigationStart) {
                this.loading = true;
            }

            if (data instanceof NavigationEnd) {
                this.loading = false;
            }
            console.log(data, 'route event');
        });

然后按照你的问题使用loading变量。