Orgial aritial --> Linkhtml
The problem with Angular 1 DI:ide
Angular 2 DI:spa
The service you inject to the parent component can be differnet with the one you inject to child component:code
var injector = ReflectiveInjector.resolveAndCreate([Engine]); var childInjector = injector.resolveAndCreateChild([Engine]); injector.get(Engine) !== childInjector.get(Engine);
`resolveAndCreate` & `resolveAndCreateChild` are function to create injector.component
Even here use the same service `Engine`, but the instances are different.htm
In Angular2, it looks like:blog
// child component @Component({ selector: 'child', providers: [Engine], template: '<h1> childcomponent !</h1>' }) class Child{ ... } // parnet component @Component({ selector: 'parent', providers: [Engine], template: '<h1> parent component !</h1>' }) class Parent { ... }
The `Engine` we inject into Child component is a new instance, which is not the same as parent one.token
So what if we want to share the same instance?ci
Well, If child component and parent component want the same service, then we only inject servie to parent component. The child component can access parent component's injected service.rem
So in code, it will looks like:
// child component @Component({ selector: 'child', providers: [], template: '<h1> childcomponent !</h1>' }) class Child{ ... } // parnet component @Component({ selector: 'parent', providers: [Engine], template: '<h1> parent component !</h1>' }) class Parent { ... }
We just remove 'Engine' from Child component, now they share the same service instance.
Angular 2 allows you configure the service differently:
provide(Engine, {useClass: OtherEngine})
2. useValue:
provide(String, {useValue: 'Hello World'})
3. useExisting:
provide(V8, {useExisting: Engine})
4. useFactory:
provide(Engine, {useFactory: () => { return function () { if (IS_V8) { return new V8Engine(); } else { return new V6Engine(); } } }})
Of course, a factory might have its own dependencies. Passing dependencies to factories is as easy as adding a list of tokens to the factory:
provide(Engine, { useFactory: (car, engine) => { }, deps: [Car, Engine] })