Services, DI & Communication
Angular Services
A service is a plain class that holds logic not tied to any single view — API calls, shared state, calculations, logging. Components stay focused on presentation and ask services for everything else.
What is Services in Angular?
A service is a plain class that holds logic not tied to any single view — API calls, shared state, calculations, logging. Components stay focused on presentation and ask services for everything else.
Why Services matters
Putting HTTP calls directly in components duplicates code and makes both testing and reuse hard. A service is written once, injected anywhere, and mocked easily in tests.
Services example
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class JobService {
private http = inject(HttpClient);
getJobs(city?: string): Observable<Job[]> {
const url = city ? `/api/jobs?city=${city}` : '/api/jobs';
return this.http.get<Job[]>(url);
}
apply(jobId: string): Observable<void> {
return this.http.post<void>('/api/applications', { jobId });
}
}How this works
providedIn: "root" registers a single shared instance for the whole application and lets the build remove the service entirely if nothing injects it.
Key points to remember
- Generate with ng g s name.
- Services are singletons per injector — root scope means one instance app-wide.
- Return Observables rather than subscribing inside the service, so callers control the lifecycle.
- The inject() function is the modern alternative to constructor injection.
Common mistakes with Services
- Subscribing inside the service and returning nothing, which hides errors from the caller.
- Providing a service in several components when you wanted one shared instance.
Angular Services— Interview Questions & FAQs
What does providedIn: "root" mean?+
The service is registered with the root injector, so the whole application shares one instance and no NgModule providers entry is needed. It also allows tree-shaking when the service is unused.
