How to use Angular services
Angular services provide a way to share data, functionality, and business logic across multiple components, ensuring a clean separation of concerns and reusable code architecture. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented countless Angular services across enterprise applications for data management, API communication, and shared utilities. From my expertise, the most effective approach is creating injectable services with the @Injectable decorator and proper dependency injection. This method provides centralized business logic and efficient data sharing between components.
Create injectable services using @Injectable decorator and inject them into components through dependency injection.
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable, BehaviorSubject } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class UserService {
private usersSubject = new BehaviorSubject<any[]>([])
users$ = this.usersSubject.asObservable()
constructor(private http: HttpClient) {}
getUsers(): Observable<any[]> {
return this.http.get<any[]>('/api/users')
}
updateUsers(users: any[]) {
this.usersSubject.next(users)
}
addUser(user: any) {
const currentUsers = this.usersSubject.value
this.usersSubject.next([...currentUsers, user])
}
}
The @Injectable decorator with providedIn: ‘root’ creates a singleton service available throughout the application. Services can maintain state using subjects, handle HTTP requests, and provide methods for data manipulation. Components inject services through their constructors to access shared functionality.
Best Practice Note:
This is the same service architecture we use in CoreUI Angular components for centralized data management and API communication across complex dashboard applications.