DEV Community

Cover image for Ultimate Angular Services Guide: Mind-blowing Ways Explored
Md. Maruf Rahman
Md. Maruf Rahman

Posted on • Edited on • Originally published at practicaldev.online

Ultimate Angular Services Guide: Mind-blowing Ways Explored

When I first started building Angular applications, I put all my business logic directly in components. That worked fine for small apps, but as applications grew, I found myself duplicating code, struggling with component communication, and making components harder to test. That's when I discovered Angular Services and Dependency Injection, and it completely changed how I structure applications.

Angular Services are singleton classes that provide reusable business logic, data access, and shared functionality across your application. They use Angular's Dependency Injection system, which means you don't manually create service instancesโ€”Angular does it for you and provides them wherever you need them. This makes your code more modular, testable, and maintainable.

What are Angular Services?

Angular Services provide:

  • Reusable business logic - Share code across components
  • Data access layer - Centralize API calls and data operations
  • State management - Share state between components
  • Singleton pattern - Single instance shared across the app
  • Dependency Injection - Automatic service provisioning
  • Testability - Easy to mock and test independently
  • Separation of concerns - Keep components focused on presentation

Creating a Basic Service

Create a service using the @Injectable decorator:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpHelper } from 'src/core/factory/http.helper';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {
  private url: string;

  constructor(private http: HttpHelper) {
    this.url = `${environment.ApiUrl}business`;
  }

  public GetBusinesses(data: any): Observable<any> {
    return this.http.post(`${this.url}/get`, data);
  }

  public GetBusiness(businessId: number): Observable<any> {
    return this.http.get(`${this.url}/${businessId}/details`);
  }

  public SaveBusiness(data: any, businessId: number): Observable<any> {
    return this.http.post(`${this.url}/${businessId}/details`, data);
  }
}
Enter fullscreen mode Exit fullscreen mode

Using Services in Components

Inject services into components via constructor:

import { Component, OnInit } from '@angular/core';
import { BusinessService } from 'src/services/business.service';

@Component({
  selector: 'app-business-list',
  templateUrl: './business-list.component.html'
})
export class BusinessListComponent implements OnInit {
  public businesses: any[] = [];
  public loading: boolean = false;

  constructor(private businessService: BusinessService) {}

  ngOnInit(): void {
    this.loadBusinesses();
  }

  private loadBusinesses(): void {
    this.loading = true;
    this.businessService.GetBusinesses({}).subscribe({
      next: (response) => {
        this.businesses = response.data;
        this.loading = false;
      },
      error: (error) => {
        console.error('Error:', error);
        this.loading = false;
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Service Providers

Different ways to provide services:

// Application-wide singleton (recommended)
@Injectable({
  providedIn: 'root'
})
export class GlobalService { }

// Module-scoped service
@Injectable()
export class ModuleService { }

// Component-scoped service
@Component({
  providers: [ComponentService]
})
export class MyComponent { }
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Use providedIn: 'root' for singleton services
  2. Inject services via constructor
  3. Keep services focused on single responsibility
  4. Use services for business logic, not presentation
  5. Make services testable and mockable
  6. Document service APIs clearly

๐Ÿ“– Read the Complete Guide

This is just a brief overview! The complete guide on my blog includes:

  • โœ… Service with HTTP Client - Complete HTTP service examples
  • โœ… Service Providers - providedIn options, module-level, component-level
  • โœ… Service Communication Patterns - BehaviorSubject, state management
  • โœ… Injecting Services into Other Services - Service dependencies
  • โœ… Service Factory Pattern - Factory providers and tokens
  • โœ… Service Testing - Complete testing strategies
  • โœ… Common Service Patterns - Data services, utility services, auth services
  • โœ… Error Handling - Complete error handling patterns
  • โœ… Real-world examples from production applications

๐Ÿ‘‰ Read the full article with all code examples here


What's your experience with Angular Services? Share your tips in the comments! ๐Ÿš€

For more Angular guides, check out my blog covering Component Communication, Reactive Forms, Routing, and more.

Top comments (0)