Injecting Services in Components

Tutorial 3 of 5

1. Introduction

This tutorial aims to provide a comprehensive guide on how to inject services into Angular components. Services in Angular allow us to encapsulate and share functionalities across different components. By injecting these services, we can leverage the same functionality in diverse parts of our application without having to duplicate code.

By the end of this tutorial, you will be able to:

  • Understand the concept of services and dependency injection in Angular
  • Create a service
  • Inject a service into a component

Prerequisites:

  • Basic understanding of TypeScript and Angular
  • Angular CLI installed in your system

2. Step-by-Step Guide

2.1 Creating a Service

  1. First, we will create a service using Angular CLI with the command: ng generate service MyService. This will create a my-service.service.ts file.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  constructor() { }
}

The @Injectable() decorator specifies that this class can be used with a dependency injector.

2.2 Injecting the Service into a Component

  1. To inject the service into a component, first import the service.
import { MyServiceService } from './my-service.service';
  1. Then, you add it to the constructor of the component where you want to use it.
constructor(private myService: MyServiceService) { }

3. Code Examples

Here's an example of a service and how to inject it into a component.

3.1 Creating a Service

Let's create a simple service that logs messages.

// message.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

In this service, we have an array of messages and two methods: add() to add a message and clear() to clear all messages.

3.2 Injecting the Service into a Component

Now we'll inject the MessageService into a component.

// app.component.ts
import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(public messageService: MessageService) { }
}

In the component's constructor, we are injecting the service we just created. We can now use the methods of the MessageService in the AppComponent.

4. Summary

In this tutorial, we learned about Angular services, how to create them, and how to inject them into components. We also looked at an example where we created a message logging service and injected it into a component.

For further learning, you could explore how to use these services to share data between components, or how to use services for HTTP requests.

5. Practice Exercises

  1. Create a service that performs basic arithmetic operations (Addition, Subtraction, Multiplication, and Division) and inject it into a component.

  2. Create a service that maintains an array of users (Add, Delete, Update, and Get users) and inject it into a component.

  3. Create a service that interacts with a mock API using HttpClient and inject this service into a component to display the data.

Remember, the key to mastering Angular Services and dependency injection is practice. So, make sure to create various services and inject them into different components to understand better how they work.