I read this article and watched these videos about Dependency Injection in Angular 2:
Vojta Jina - Dependency Injection - NG-Conf
Dependency Injection in Angular 2 by Pascal Precht
and quite understand about DI in Angular. But I'm confused on how to use it right.
My question is when to use Type Definition(1) like this:
import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'example-component',
template: '<div>I am a component</div>'
})
class ExampleComponent {
constructor(private http: Http) {}
}
And when to use Injector(2) like this:
import { Injector, provide } from 'angular2/core'
var injector = Injector.resolveAndCreate(
[
provide(SomeObj, {useClass: SomeObj})
]);
The second one gets me confused as I'm not sure where it's supposed to go (Component, Service, or else?), how to consume it?
First thing to note is that resolveAndCreate method is called on ReflectiveInjector like this (not Injector):
import { ReflectiveInjector } from '@angular/core';
const customInjector = ReflectiveInjector.resolveAndCreate( ... )
The second thing is that ReflectiveInjector is deprecated in favor of StaticInjector. Read more about it in Angular deprecates ReflectiveInjector and introduces StaticInjector. Should you care?
So now if you want to create a custom injector you should use StaticInjector can do like this:
import { HttpClient } from '@angular/common/http';
const customInjector = new StaticInjector([
{provide: `MyCustomToken`, useValue: 'just a string value', deps: [HttpClient]}
])
The second one gets me confused as I'm not sure where it's supposed to go
Custom injectors created using either reflective or static injector can be passed to either module or component factory when instantiating them. Here are some examples from the article Here is what you need to know about dynamic components in Angular:
const customInjector = new StaticInjector( ... );
// module
this.loader.load('app/t.module#TModule').then((klass) => {
const factory = compiler.compileModuleSync(klass);
const module = factory.create(customInjector);
// dynamic component
const r = module.componentFactoryResolver;
const cmpFactory = r.resolveComponentFactory(AComponent);
const componentRef = cmpFactory.create(customInjector);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With