简体   繁体   中英

DI in angular 2

I m actually studying the angular DI container and I need some informations.

In fact, reading the API, it seems that the Injector class accepts a Binding list in the factory arguments, and resolve it to acquire a ResolvedBinding list.

NB : https://angular.io/docs/js/latest/api/di/

I was wondering how the system is able to manage the conversion between Binding and ResolvedBing because :

  • Binding can return a value
  • Binding can return an alias
  • Binding can return a class
  • Binding can return a factory

The ResolvedBinding constructor is the following :

constructor(key:Key, factory:Function,...)

It seems that it's okay to return a factory when the needed is there (and class, if we admit that class are created through factories everytime), but what if I need to return only a value ? Does the fw creates a factory to specifically return the value ?

A binding that is passed to the injector creation doesn't really return one of those values. A binding literally represents the binding configuration itself.

And as you might know, a binding get's a token and uses a factory function to tell the injector how to create and instance of a specific type. So the factory function that you're mentioning here, can be .toClass() , .toFactory() , .toValue() .

The recipe is normalised before creating a ResolvedBinding out of it. Here's are the LOC that should clear things up: https://github.com/angular/angular/blob/master/modules/angular2/src/di/binding.ts#L221-L246

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