Skip to the content.

πŸ“˜ Angular > Services

πŸ—οΈ Angular Services

Angular services are used to share data, logic, and functionality across different components in an application. They are a fundamental part of Angular’s dependency injection system, allowing you to create reusable and testable code.

When you create a new service using Angular CLI, you’ll get the following structure:

my-first-app/
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ my-service/
β”‚   β”‚   β”‚   β”œβ”€β”€ my-service.service.ts    # Service logic
β”‚   β”‚   β”‚   └── my-service.service.spec.ts # Service unit tests

Services are typically used for tasks like fetching data from APIs, managing application state, or encapsulating business logic.


πŸ› οΈ Creating a Service with Angular CLI

You can create a new service using the Angular CLI:

ng generate service my-service

This command will:


πŸ“„ Anatomy of a Service

A typical Angular service consists of the following:

  1. TypeScript File (.service.ts): Contains the logic and functionality of the service.
  2. Spec File (.service.spec.ts): Contains unit tests for the service.

Example of a service’s TypeScript file:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // Makes the service available application-wide
})
export class MyService {
  private data: string[] = [];

  addData(item: string) {
    this.data.push(item);
  }

  getData(): string[] {
    return this.data;
  }
}

πŸ“œ Key Features of Services


🌟 Example: A Simple Data Service

Here’s an example of a simple data service:

Service File (data.service.ts):

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private items: string[] = [];

  addItem(item: string) {
    this.items.push(item);
  }

  getItems(): string[] {
    return this.items;
  }
}

Using the Service in a Component (app.component.ts):

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <input [(ngModel)]="newItem" placeholder="Add an item" />
      <button (click)="addItem()">Add</button>
      <ul>
        <li *ngFor="let item of items"></li>
      </ul>
    </div>
  `
})
export class AppComponent {
  newItem: string = '';
  items: string[] = [];

  constructor(private dataService: DataService) {}

  addItem() {
    this.dataService.addItem(this.newItem);
    this.items = this.dataService.getItems();
    this.newItem = '';
  }
}

πŸ”„ Lifecycle of a Service

Angular services are instantiated and managed by Angular’s dependency injection system. The lifecycle of a service depends on its provider scope:

Example of component-level service:

@Component({
  selector: 'app-example',
  template: `<p>Example Component</p>`,
  providers: [MyService] // Service is scoped to this component
})
export class ExampleComponent {}

Understanding Angular services is essential for managing shared logic and state in your application. Mastering services will help you create scalable, maintainable, and testable Angular applications.