Orgial aritial---Link
The problem with Angular 1 DI:
Angular 2 DI:
- Solve the singletons problem:
The service you inject to the parent component can is differnet with the one you inject to child component:
var injector = reflectiveinjector.resolveandcreate ([Engine]); var childinjector =!== childinjector.get (Engine);
' Resolveandcreate ' & ' Resolveandcreatechild ' is function to create injector.
Even here and the same service ' Engine ', but the instances is different.
In Angular2, it looks like:
// Child Component @Component ({ ' child ', providers: [Engine], ' }) Class child{... } // parnet Component @Component ({ ' parent ', providers: [Engine], ' }) class Parent { ...}
The ' Engine ' we inject into child component are a new instance, which is not the same as parent one.
So, if we want to share the same instance?
Well, If child component and parent component want the same service, then we are inject servie to parent component. The child component can access parent component ' s injected service.
So in code, it'll looks like:
// Child Component @Component ({ ' child ', providers: [], ' }) class child{... } // parnet Component @Component ({ ' parent ', providers: [Engine], ' }) class Parent { ...}
We just remove ' Engine ' from child component, now they share the same service instance.
- Solve Name Collision Problem:
Angular 2 allows you configure the service differently:
- Useclass:
Provide (Engine, {useclass:otherengine})
2. Usevalue:
Provide (String, {usevalue: ' Hello World '})
3. Useexisting:
Provide (V8, {useexisting:engine})
4. Usefactory:
Provide (Engine, {usefactory: () = { returnfunction () { if (IS_V8) { returnnew v8engine (); Else { returnnew v6engine ();}}} )
Of course, a factory might has its own dependencies. Passing dependencies to factories are as easy as adding a list of tokens to the factory:
provide (engine, { = = { }, deps: [Car, Engine]})
[Angular 2] DI in Angular 2-1