2016-11-02 62 views
0

我使用下面的微調從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); 
    } 
} 

所以對於我不得不進口其每一個組成部分,我想避免它,因爲許多組件將使用它。我怎樣才能使整個應用程序可用?

+0

從每個消費者導入都有一些好處,主要是調出依賴關係。想象一下,在沒有'import {SpinnerService}從...行'的條件下搜索並替換它。 – ssube

+0

但是,特定於應用程序中的微調器服務通常對於所有組件都是相同的。如果它改變,那麼整個應用程序將被更新 – FacundoGFlores

回答

1

可以創建一個基體組分和放像

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() 

ReflectiveInjector可以的@角/芯內部中找到

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

+0

appInjector是什麼?你從哪裏進口? – FacundoGFlores

+0

@FacundoGFlores'從'@ angular/core'導入{Injector};' –

+0

@FacundoGFlores我已經更新了答案,請記住這是服務定位器模式,僅供參考。 –