使用微调器作为全局服务 [英] Using spinner as global service

查看:92
本文介绍了使用微调器作为全局服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以创建一个基本组件并放置一个类似

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

然后使用它:

this.spinnerService.show()

ReflectiveInjector 可以在 @ angular/core

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

这篇关于使用微调器作为全局服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆