07345159778
support@getskillonline.com

Services and Dependency Injection

Lesson 2/3 | Study Time: 60 Min
Services and Dependency Injection

Module 2: Services and Dependency Injection (1 Hour)


● Services (30 minutes)

○ What are services?


■ Services are reusable classes that provide functionality to other parts of your application(components, other services).

■ They encapsulate logic that can be shared across multiple components, promoting code reusability and maintainability.


■ Common use cases:

■ Fetching data from an API.

■ Sharing data between components.

■ Implementing business logic.

■ Logging.


○ Creating services:

■ Use the Angular CLI to generate services.

■ Use the @Injectable() decorator to mark a class as a service.


○ Injecting services:

■ Use constructor injection to inject services into components or other services.

■ Angular's dependency injection system provides the required service instance.


○ Using services:

■ Call the methods of the injected service to access its functionality.


○ Example:

■ Generate a service: ng generate service log log.service.ts:







My.component.html:


<button (click)="doSomething()"Do Something<button>


● Dependency Injection (30 minutes)

○ What is dependency injection?

■ Dependency injection (DI) is a design pattern in which a class receives its dependencies from external sources rather than creating them itself.

■ In Angular, DI is a core mechanism for managing and providing dependencies, such as services, to components and other services.


○ Why use dependency injection?

■ Decoupling: Reduces dependencies between classes, making code more modular and easier to maintain.

■ Testability: Makes it easier to test components and services by providing mock dependencies.

■ Reusability: Promotes the reuse of services across the application.

■ Maintainability: Simplifies managing complex application dependencies.


○ How DI works in Angular:

■ Providers: Define how to create a dependency. A provider can be a class itself, a factory function, or a value.

■ Injectors: Objects that manage dependencies and provide them to requesting classes. There's at least one injector per Angular application, and there can be hierarchical injectors.


■ @Injectable(): Decorator that marks a class as a service, making it eligible for injection. The providedIn property specifies which injector will provide the service.

■ Constructor injection: The most common way to receive dependencies. List the dependencies as parameters in the constructor of the class that needs them. Angular's injector will provide the instances.


○ Example:



○ In this example:

■ GreetingService is marked as injectable.

■ DiExampleComponent&#39;s constructor declares that it needs an instance of GreetingService.


■ Angular's DI system provides the instance of GreetingService when DiExampleComponent is created.