Angular2使用加载栏更改路径

时间:2017-03-26 18:01:08

标签: angular angular2-routing angular2-services

我正在寻找最好的做法。当我改变路线时,我想要一个加载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();
}

你还有其他任何建议......用“一次性代码”而不是每个组件......?

1 个答案:

答案 0 :(得分:1)

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

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变量。