Back to results for “Dependency injection”
Angular › Services & Dependency Injection

What is a service in Angular and why are services used to hold shared logic?

Beginner

Answer

A service is a class dedicated to a specific piece of functionality, such as fetching data from a server or managing shared application state, kept separate from components so that logic can be reused across many different components without duplicating code.
@Injectable({ providedIn: 'root' })
export class UserService {
  getUsers() {
    return this.http.get('/api/users');
  }
  constructor(private http: HttpClient) {}
}
Real-world example Several completely different components across an app all use the same UserService to fetch user data, avoiding the need for each component to duplicate that same fetching logic on its own.

Common follow-ups: Why should components generally avoid containing complex business logic themselves?;What does the Injectable decorator actually do?