Typescript / Angular 4:注入服务和初始化为新类是什么区别



我想知道这两个示例之间有什么区别:

export class EditorComponent {
  constructor(
      public _entryService: EntryService
  ){
      console.log(this._entryService.entryData.properties);
   }
}

export class EditorComponent {
  _entryService;
  constructor(){
     this._entryService = new EntryService;
     console.log(this._entryService.entryData.properties);
  }
}

两者之间有任何实际区别吗?

我预计我对基本理论的了解可能会有一些差距 - 任何方向都可以帮助我自我教育的方向,这将不胜感激 - 谢谢!

this._entryService = new EntryService的等效是组件定义中的提供商:

@Component({ ..., providers: [EntryService] })
export class EditorComponent {
  constructor(
      public _entryService: EntryService
  ){}
}

这将根据每个组件实例创建新的EntryService实例。

如果没有提供商属于组件喷油器,则将从父型喷油器(可能是根本喷油器)中检索,并且会导致EntryService提供商的单个实例:

@Component({ ..., providers: [] })
export class EditorComponent {
  constructor(
      public _entryService: EntryService
  ){}
}

唯一需要new EntryService的情况是当类构造器接受非DI参数时(如本示例所示)。

最新更新