我使用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 :(得分:1)
您可以创建基本组件并添加类似
的getterexport 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