Invisible Architects of Scalable Apps Services & Dependency

Ever wondered how Angular apps seem to effortlessly manage complex logic and dependencies? The secret often lies in the behind-the-scenes magic of services and dependency injection (DI). While they may sound like buzzwords, these Angular features are the unsung heroes that power your app’s scalability and maintainability.

In this article, we will dive deep into what services are, how to create and use them, and how Angular's DI system can save you time and headaches when managing dependencies. Think of this as your backstage pass to mastering Angular's architecture, where we will untangle the complexity of DI and show you how to leverage it to make your app more modular, testable, and—most importantly—efficient.

Let’s get started and unlock the power of services and DI in Angular!

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

  1. Create your angular project
  2. 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:

    In the project, the following will appear:

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

  4. 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.

  1. 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
    First service
  2. 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.
    App component
  3. 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

Services and dependency injection are fundamental concepts in Angular that help structure your application in a modular, maintainable, and testable way. By using services, you can encapsulate reusable logic and share data across multiple components, while dependency injection ensures that these services are provided in a flexible and efficient manner. Setting up DI correctly allows for loose coupling between components and services, making your code easier to scale and modify as your application grows. With a solid understanding of services and DI, you can write cleaner, more maintainable code that adheres to best practices in Angular development.

Up Next
    Ebook Download
    View all
    Learn
    View all