How to inject a service into a component in Angular
Injecting services into Angular components enables access to shared functionality, data, and business logic through Angular’s dependency injection system. As the creator of CoreUI, a widely used open-source UI library, I’ve injected services into thousands of Angular components across enterprise applications for data management and API communication. From my expertise, the most effective approach is using constructor injection with proper TypeScript typing and access modifiers. This method provides clean service access with automatic instantiation and lifecycle management.
Inject services into component constructors using dependency injection with proper TypeScript typing.
import { Component, OnInit } from '@angular/core'
import { UserService } from '../services/user.service'
import { NotificationService } from '../services/notification.service'
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
users: any[] = []
loading = false
constructor(
private userService: UserService,
private notificationService: NotificationService
) {}
ngOnInit() {
this.loadUsers()
}
async loadUsers() {
try {
this.loading = true
this.users = await this.userService.getUsers().toPromise()
this.notificationService.showSuccess('Users loaded successfully')
} catch (error) {
this.notificationService.showError('Failed to load users')
} finally {
this.loading = false
}
}
}
Services are injected through the component constructor using private access modifier for automatic property creation. Angular’s dependency injection system automatically provides service instances based on the constructor parameters. Use proper TypeScript typing and access modifiers for clean, maintainable code.
Best Practice Note:
This is the same dependency injection pattern we use in CoreUI Angular components for accessing shared services and maintaining clean component architecture.