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);
}
}
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;
}
});
}
}
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 { }
Best Practices
- Use
providedIn: 'root'for singleton services - Inject services via constructor
- Keep services focused on single responsibility
- Use services for business logic, not presentation
- Make services testable and mockable
- 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)