Dependency Injection Flashcards
1
Q
What is Dependency Injection?
A
- It is an important application design pattern.
- This increases the efficiency and modularity.
- They are services or objects that a class needs to perform its function.
- It is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself.
2
Q
@Injectable decorator
A
@Injectable({ providedIn: ‘root’ })
export class xyzService{
getXyz() { return abc; }
}
- The class is a service.
- The injectable decorator markts it as a service that can be injected.
- The injector is responsible for creating service instances and injecting them into classes.
- A provider tells an injector how to create the service.
- Injector has to be configured in the provider.
- It can be configured at different levels
- @Injectable() decorator
- @NgModule() decorator
- @Component() decorator
- When generating services, it is adding extra metadata with a ‘provided in’ property with a default of ‘root’ (it can be any module of the application)
- If ‘root’ is used then injectable will be registered as a singleton in the application and it is not needed to be added to the providers of the root module.
- If ‘UserModule’ is used then the injectable is registered as a provider of the userModule without adding it to the providers in the module.
- The better option is to provide it in @NgModule() - otherwise it will be plauged with circular dependencies.
3
Q
Configure injectors
A
- By using providedIn metadata option - with root injector or the injector for a specific NgModule. @Injectable({ providedIn:’root’}) – provides this service in the root
- The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors. @Component({ providers: [{provide: abcService, useValue: { name:’lmp’} }] }) —This is visible only at component.
- @NgModule()
4
Q
Injector hierarchy
A
There is only one root injector for an app.