TypeScript 构造函数中的私有变量声明以诱导 DI

Gan*_*nya 3 dependency-injection angularjs typescript

为了在 Angular 2 中使用 TypeScript 引入依赖注入,我们使用如下代码:

constructor(private _service : SampleService){}
Run Code Online (Sandbox Code Playgroud)

我想知道private关键字在此处变量声明中的重要性。如果我们不声明服务 a 会影响private吗?

谢谢

Cod*_*ior 5

constructor(private _service : SampleService){} 是注入您希望在组件中使用的服务的推荐方法。

如果不使用private,则必须编写更多代码行来访问构造函数之外的注入服务,如下所示:

class CompClass {
  private _service: SampleService;
  constructor(service : SampleService) {
    this._service = service;
  }

  doSomething() : void {
    this._service.makeServiceCall();
  }
}
Run Code Online (Sandbox Code Playgroud)