Search code examples
angularangular2-routingangular2-services

Angular2 Changing routes with loading bar


I'm looking for the best practice. When I'm changing route I want a loading gif. So I create a service

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

@Injectable()
export class LoadingService {

public active = false;

constructor() { }

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

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

}

and a component

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

}

So I'm injecting this service to components and on ngOnInit and ngOnDestroy

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

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

Do you have any other suggestion... With "one time code" and not to every component..?


Solution

  • Within your root app component you could subscribe to the router events, something like this :-

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

    Then use the loading variable as you are in your question.