简体   繁体   中英

Angular 2 di container

I m actually studying Angular 2 and I was wondering how does the team do to handle dependency injection in their component ?

Explanation

It seems that Ng2 is based on ES7 decorator through TypeScript. In fact, class decorator is "launch" (I mean, the code of the decorator) is only interpreted when the class is instanciated.

So, how does the team do to handle component / service injection ?

Example

Looking at this code from the documentation :

class AComponent {
  constructor(@Inject(MyService) aService:MyService) {}
}

The injection is made when the constructor of the class is called. This means that MyService has a certain decorator/specific metadata (like @Injectable) that allows him to be injected no ?

In this case, it means that there is a registry of services, a list of them accessible through the @Inject annotation.

But this means that the framework is able to create and load this repository at runtime (this is the important word), which doesn't match with the decorator call (at instanciation for class annotations) ?

Is this mean that every component/services injectable are instanciated at least one time ? Or does it exist something else to inject or execute some decorator at runtime to fill the service registry/container ?

Thanks for advance

In fact, class decorator is "launch" (I mean, the code of the decorator) is only interpreted when the class is instanciated.

The injector yes. But Component no, and that is the piece of puzzle you are missing.

declare var Component: any;
declare var Inject: any;
declare type MyService = any;
declare var MyService: any;

@Component
class AComponent {
  constructor(@Inject(MyService) aService:MyService) {}
}

The @Component call will be made at definition time. This will allow angular to register the component. The when someone asks for said component the Constructor @Inject will execute and thus angular DI will kick in.

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