FacundoGFlores FacundoGFlores - 9 months ago 93
TypeScript Question

Using spinner as global service

I am using the following spinner from the ng2-admin theme:

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

export class BaThemeSpinner {

private _selector:string = 'preloader';
private _element:HTMLElement;

constructor() {
this._element = document.getElementById(this._selector);

public show():void {
this._element.style['display'] = 'block';

public hide(delay:number = 0):void {
setTimeout(() => {
this._element.style['display'] = 'none';
}, delay);

So for each component I have to import it, and I want to avoid it, because many components will use it. How can I make it available to the whole application?

Answer Source

You can create a base component and put a getter like

export class BaseView {

    protected _injector:Injector;

    protected _spinnerService:SpinnerService;

    constructor() {
        let providers = ReflectiveInjector.resolve([SpinnerService]);
        this._injector = ReflectiveInjector.fromResolvedProviders(providers);

    get spinnerService(): SpinnerService { 
        if (this._spinnerService == null) {
            this._spinnerService = this._injector.get(SpinnerService);
        return this._spinnerService;

then use it:


ReflectiveInjector can be found inside of @angular/core

Docs: https://angular.io/docs/ts/latest/api/core/index/ReflectiveInjector-class.html