简体   繁体   中英

Typescript / Angular 4: What is the difference between injecting a service and initializing as new class?

I am wondering what the difference is between these two examples:

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

}

Is there any practical difference between the two?

I anticipate that there may be some gaps in my knowledge of basic theory here- any pointers in a direction that will help me educate myself would be appreciated- thanks!

The equivalent of this._entryService = new EntryService is a provider in component definition:

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

This will create new EntryService instance per each component instance.

If no provider belongs to component injector, it will be retrieved from parent injector (likely root injector) and will result in single instance of EntryService provider:

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

The only case when new EntryService is desirable is when class constructor accepts non-DI arguments (like shown in this example ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM