使用微调器作为全局服务

时间:2016-11-02 18:58:13

标签: angular typescript spinner service-locator

我使用ng2-admin主题中的以下微调器:

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

因此,对于每个组件,我必须导入它,并且我想避免它,因为许多组件将使用它。如何将它提供给整个应用程序?

1 个答案:

答案 0 :(得分:1)

您可以创建基本组件并添加类似

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

然后使用它:

this.spinnerService.show()
可以在 @ angular / core

中找到

ReflectiveInjector

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