Angular2构造对象取决于DI

时间:2016-05-17 10:49:36

标签: angular

我在Angular2中有一个需要DI的课程,我正在使用打字稿,我尝试以下列方式将我的服务注入普通类。 (不是组件,我可以毫无问题地在组件中注入服务)

     constructor(@Inject(SidebarService) sidebarService : SidebarService)

在我尝试用@Inject注释类之前,希望这会使得打字稿生成必要的DI代码。

在这两种情况下,当我尝试构造对象时,我会收到一条消息,告诉我构造函数的参数缺失。

例如

        this.sidebarHelper = new ItemSidebarHelper();

会说error TS2346: Supplied parameters do not match any signature of call target.

在这种情况下使用DI的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

Regarding your comments I edited the answer for usage of a singleton service without dependency resolution:

class SidebarService {
  static instance: SidebarService;
  static instantiating: Boolean = false;

  constructor() {
    if (!SidebarService.instantiating) {
      throw new Error("Use SidebarService.getInstance()");
    }
  }

  static getInstance(): SidebarService {
    if (SidebarService.instance == null) {
        SidebarService.instantiating = true;
        SidebarService.instance = new SidebarService();
        SidebarService.instantiating = false;
    }

    return SidebarService.instance;
  }
}

class ItemSidebarHelper {
  private _sidebarService: SidebarService;
  constructor() {
    this._sidebarService = SidebarService.getInstance();
  }
}


var sidebarHelper = new ItemSidebarHelper();

Plunkr for example usage

答案 1 :(得分:0)

实际上,您可以将Angular的注入器注入您的类

@Component({
    selector: 'my-injectors',
    template: `
    <h2>Other Injections</h2>
    <div id="car">{{car.drive()}}</div>
    <div id="hero">{{hero.name}}</div>
    <div id="rodent">{{rodent}}</div>
    `,
    providers: [Car, Engine, Tires, heroServiceProvider, Logger]
})
export class InjectorComponent {
    car: Car = this.injector.get(Car);
    heroService: HeroService = this.injector.get(HeroService);
    hero: Hero = this.heroService.getHeroes()[0];
    constructor(private injector: Injector) { }
    get rodent() {
        let rousDontExist = `R.O.U.S.'s? I don't think they exist!`;
        return this.injector.get(ROUS, rousDontExist);
    }
}

来自:https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector