Back to all posts

Angular: Services


Services are a key part of building a scalable and maintainable Angular application. Services are used to organize and share code across your application. They typically contain business logic, data management, or other reusable code that can be injected into Angular components, directives, or other services.


Creating and Using a Service in Angular

1. Generate a Service: Use the Angular CLI to generate a service:

ng generate service service-name

This creates two files: service-name.service.ts and service-name.service.spec.ts.

2. Define Logic in the Service

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

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

  getData() {
    return this.data;
  }

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

3. Inject the Service into a Component:

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

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

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.items = this.dataService.getData();
  }

  addItem() {
    this.dataService.addData('New Item');
    this.items = this.dataService.getData();
  }
}

4. Service Scope and Providers:

  1. The @Injectable({ providedIn: 'root' }) decorator makes the service available throughout the app.
  2. For a limited scope, you can provide a service in a specific module or component:
@NgModule({
  providers: [DataService],
})
export class SomeModule {}

5. Sharing Data Across Components: Services are often used for sharing data between components:

  • Example: A UserService can store user information that multiple components need.

Key Features of Angular Services:

  1. Reusability: Services encapsulate logic that can be reused across different parts of the application.
  2. Dependency Injection (DI): Services are injected into components or other services, promoting loose coupling.
  3. Singletons: By default, services provided at the root level are singleton instances, meaning the same instance is shared throughout the application.
  4. Separation of Concerns: They help keep components focused on presentation logic by delegating other tasks to services.