Have you ever wondered how Angular apps seem to handle intricate dependencies and logic with ease? The magic that happens behind the scenes with services and dependency injection (DI) is frequently the key. These Angular features are the unsung heroes that drive the scalability and maintainability of your app, despite the fact that they might sound like catchphrases.

In-depth discussions of services, their creation and usage, and how Angular's DI system may help you manage dependencies more efficiently will all be covered in this article. Consider this your backstage ticket to learning the architecture of Angular, where we will unravel the intricacies of DI and demonstrate how to use it to improve the modularity, testability, and—above all—efficiency of your application.

Let's get started and discover Angular's services and DI capability!

Services
For an easier understanding, we will use the analogy of a remote control.
You do not need to go up to the TV to change channels, adjust the volume, or turn it on and off. You just use the remote (service), which is always there, to perform these actions from a distance.

In Angular, services are like this remote. Components don’t need to directly handle or interact with complex logic or data—they just "press a button" (call a service method), and the service handles the rest. It simplifies things and keeps everything within easy reach.

Another important aspect is reusability. With a universal remote control, you can control multiple devices. Instead of having to adjust each device manually or have a separate remote for each, the universal remote lets you control all these devices with just one tool.

In Angular, a service is a reusable piece of code that you can "call" from any component in your app. Whether it is fetching data, performing a calculation, or handling complex logic, you don’t have to rewrite the same functionality in multiple components. You simply "press the button" (call the service) wherever it is needed, and the service does the job, ensuring that your app remains clean, DRY (Don’t Repeat Yourself), and easy to maintain.

Services maximize reusability and provide a better code structure for your project.

When to use a service?

In Angular, a service should be used when you need to:

  • Share data or logic across components: Services provide a central place where data or business logic can be shared across multiple components, so you don't have to duplicate code in each component.
  • Encapsulate business logic: If you have complex logic or operations that don’t belong directly in a component, putting them in service makes your code cleaner and more maintainable.
  • Make HTTP requests: Services are commonly used for interacting with back-end APIs. Instead of having HTTP requests directly inside components, you use services to handle all the communication with the server.
  • Manage state: Services can manage the state of your application, like keeping track of user authentication, settings, or preferences, and can keep this state consistent across components.
  • Improve testability: By separating business logic into services, you can more easily write unit tests for that logic. It also allows mocking or stubbing services in tests to isolate components.

Creating a service

  • Create your angular project
  • Create the service you need using the following command

ng generate service <<name of the service>>

If you need to create the service in a specific file, you can modify the command slightly as follows:
ng generate service <<folder-path/name_of_the_service>>

For our demo, we will create our service in the ‘my-services-folder’ folder and call it ‘my-first-service’. We will use this command: ng generate service my-services-folder/my-first-service

Once the command is successfully executed, you will see the following:

The project will include the following:

When you open the service.ts file, you will see the following file already created for you:

You can start writing your functions under the constructor [as from line 9].

Note. A common practice is to have API calls in services. For the sake of simplicity, a function returning a welcome note is used in our example.

At this point, we have successfully created a service.

Inject and use a service

Think of it like this: if you are building a car, instead of the car having to make its own engine, wheels, and seats, someone (like a supplier) gives those parts to the car so it can assemble them.

Dependency injection (DI) is a way to provide components with access to services and other resources.

In our example, we will inject our ‘MyFirstService’ in the ‘app component’ and use the getGreeting function. This will allow us to reuse the function. Remember that, the same steps apply to any component you would want to inject the service.

Open the component you want to inject the service and pass the service in the constructor.
In our case, we will do it in the app.component.ts

Create a function that will call the required function from the service. You can also call it from the ngOnInit as well. It all depends on your use cases.

Create the html template to get and display the information and trigger the function call.
In our case, we will create in the app.component.html

Note. On line 2, we are using [(ngModel)]. This is called 2-way binding.
When using it, you need to add ‘FormsModule’ under ‘imports’ in the component’s module file; in our case, app.module.ts.


Below is what the end result looks like:


Conclusion
Angular's core ideas of services and dependency injection aid in organizing your application in a way that is modular, testable, and manageable. Dependency injection makes sure that these services are delivered in a flexible and effective way, while services allow you to encapsulate reusable functionality and communicate data across many components. Correct DI setup enables loose connection between services and components, which facilitates code scalability and modification as your application expands. You can write code that follows best practices in Angular development and is cleaner and easier to maintain if you have a firm grasp of services and DI.