Angular › Services & Dependency Injection
What is a service in Angular and why are services used to hold shared logic?
BeginnerAnswer
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.