Using spinner as global service

时间秒杀一切 提交于 2020-01-17 11:15:23

问题


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

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

@Injectable()
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?


回答1:


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:

this.spinnerService.show()

ReflectiveInjector can be found inside of @angular/core

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



来源:https://stackoverflow.com/questions/40387738/using-spinner-as-global-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!