简体   繁体   中英

How does Angular2 manage dependency injection?

I understand that to inject a dependancy into an Angular2 component, I simply annotate an argument in its constructor, like here with ThingService . What I would like to understand is how Angular knows what to inject at runtime, as so far as I am aware, this is just TypeScript annotation and has no meaning at run time. What is the low level, internal mechanism of this to manage which providers are placed where in a component's constructor. If you were to roll this system yourself, how would it work. Is this a typescript mechanism I am not understanding?

@Component({
  selector: 'app-thing',
  templateUrl: './thing.component.html',
  styleUrls: ['./thing.component.scss']
})
export class ThingComponent {

  constructor(
    private thingService: ThingService) {
  }
}

What happens under the hood is that TypeScript preserves the metadata in the generated ES5 code. So the annotation in your constructor isn't actually gone, it's available at runtime and then Angular's DI can take it from there.

TypeScript always preserves that metadata if the following requirements are fulfilled:

  1. Both compiler option properties - emitDecoratorMetadata and experimentalDecorators - need to be set to true
  2. There has to be at least one decorator on the class (that's why some service classes use the @Injectable() decorator, otherwise the metadata for their dependencies won't be emitted)

I've written an in-depth article about that topic here

If I understood correctly you are asking for a more theoretical(js behind the ts) answer.

According to what I've read; angular2 injection system creates an instance of that provider object/function and uses that instance in that component when you define it like that in the constructor. If you haven't provided it in the component that you are using then it will go to it's parent component, up to the module that it's been used. Each level has its own map of provider instances and the component will use the first instance that it finds when it traverses the injection tree upwards.

So the provider will be a singleton instance up to the point it is defined.

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