I need to either use providers: []
For dependency injection to be able to create instances for you, you need to register providers for these classes (or other values) somewhere.
Where you register a provider determines the scope of the created value.
Angulars DI is hierarchical.
If you register a provider at the root of the tree
>=RC.5
@NgModule({
providers: [/*providers*/]
...
})
or for lazy loaded modules
static forRoot(config: UserServiceConfig): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
{provide: UserServiceConfig, useValue: config }
]
};
}
<=RC.4
(bootstrap(AppComponent, [Providers})
or @Component(selector: 'app-component', providers: [Providers])
(root component)
then all components and services that request an instance get the same instance.
If a provider is registered in one of the child components a new (different) instance is provided for descendants of this component.
If a component requests an instance (by a constructor parameter), DI looks "upwards" the component tree (starting from leaf towards the root) and takes the first provider it finds. If an instance for this provider was already created previously, this instance is used, otherwise a new instance is created.
@Inject()
When a component or service requests a value from DI like
constructor(someField:SomeType) {}
DI looks up the provider by the type SomeType
. If @Inject(SomeType)
is added
constructor(@Inject(SomeType) someField:SomeType) {}
DI looks up the provider by the parameter passed to @Inject()
. In the above example the parameter passed to @Inject()
is the same as the type of the parameter, therefore @Inject(SomeType)
is redundant.
However there are situations where you want to customize the behavior for example to inject a configuration setting.
constructor(@Inject('someName') someField:string) {}
The type string
isn't sufficient to distinguish a specific configuration setting when you have a several registered.
The configuration value needs to be registered as provider somewhere like
>=RC.5
@NgModule({
providers: [{provide: 'someName', useValue: 'abcdefg'})]
...
})
export class AppModule {}
<=RC.4
bootstrap(AppComponent, [provide('someName', {useValue: 'abcdefg'})])
Therefor you don't need @Inject()
for FormBuilder
if the constructor looks like
constructor(formBuilder: FormBuilder) {}
@Inject
for FormBuilder. – Yirinec