2016-11-02 64 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我已经更新了答案,请记住这是服务定位器模式,仅供参考。 –