Services and Dependency Injection Flashcards
What are services?
Services are:
- Class with focused purpose
- Used for features that are independent from any particular component
- Used for providing shared data or logic across components
- Encapsulate external interactions
How many ways for using service?
1 Way: (bad) Component can create instance of service class and use it. But instance is local to the component and it's difficult to mock the service
2 Way:
Register service with angular. Angular creates a singleton service instance. Angular has a built in injector. It maintains a container of services.
If component needs service, it define the service as a dependency.
Dependency injection is
A coding pattern in which a class receives the instance of objects it needs (called dependencies) from an external source rather than creating them itself.
In angular the external source is the angular injector.
What to do in order to create a service?
- Create class
2. Add @Injectable() decorator
How many ways for registering a service
Two. Root injector or Component injector.
What Root injector does?
Service is available throughout the application.
Recommended for most scenarios
What Component injector does?
Service is only available to that component and its child (nested) components.
Isolates a service used by only one component.
Provides multiple instances of the service.
How to register service in root application
In @Injectable decorator set {
providedIn: ‘root’
}
How to register service for specific component
In @Component decorator in the component itself add {…
providers: [ProductService]
}
How the service is injected?
Define it as a depndency.
export class ProductionListComponent { private _productService; constructor(productService: ProductService) { this._productService = productService; } }
A sort cut of this is
constructor(private productService: ProductService)