Sub topic 3
Putting HTTP Calls in a Data Service
This chapter assumes you know TypeScript classes and interfaces, Angular dependency injection, and that you have already registered HttpClient with provideHttpClient() as shown in the previous chapter. Here you will move HTTP calls out of components and into a dedicated data service.
Why a Service Owns the HTTP Calls
A data service is an injectable class that hides how data is fetched. Components ask the service for data and never build URLs or call HttpClient themselves.
This split pays off in several ways:
- One place for endpoints. If
/api/todosbecomes/api/v2/todos, you change one line. - Reuse. Several components can share the same method.
- Testing. You can test the service on its own and replace it with a fake in component tests.
- Thin components. Components stay focused on rendering and user input.
Injecting HttpClient
Modern Angular code uses the inject() function to get dependencies. You call it in a field initializer, which runs inside an injection context.
// todo.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl);
}
}Several choices in this code matter:
providedIn: 'root'creates one shared instance for the whole app. Angular can tree-shake the service if nothing injects it.private readonlystops components from reaching through the service to callhttpdirectly.- The method returns the Observable and does not subscribe to it. The caller decides when the request runs and what to do with the result.
Constructor injection still works
Older code and some teams prefer constructor parameters. The behavior is the same:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class LegacyTodoService {
constructor(private readonly http: HttpClient) {}
}Pick one style and use it across the codebase. inject() works better with inheritance and functional APIs such as interceptors, which you will meet later.
Using the Service from a Component
The component injects the service, not HttpClient:
import { Component, OnInit, inject } from '@angular/core';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-count',
template: `<p>{{ todos.length }} todos</p>`
})
export class TodoCountComponent implements OnInit {
private readonly todoService = inject(TodoService);
todos: Todo[] = [];
ngOnInit(): void {
this.todoService.getTodos().subscribe(todos => (this.todos = todos));
}
}A later chapter replaces this manual subscribe with the async pipe or toSignal, which clean up automatically.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing from the app config | Add it to `providers` in `app.config.ts` |
| `NG0203: inject() must be called from an injection context` | `inject()` called inside a method or callback | Call it in a field initializer or the constructor |
| No request appears in the Network tab | The Observable was never subscribed | Subscribe, or use the async pipe or `toSignal` |
| Service subscribes and stores data internally | Results are hard to compose or cancel | Return the Observable and let callers subscribe |
Exercises
Exercise
A developer moves inject(HttpClient) from a field initializer into the body of getTodos(). What happens and why?
Show answer
Angular throws NG0203 when the method runs, because inject() only works inside an injection context such as a field initializer or constructor, and a regular method call isn't one.
Exercise
Why should getTodos() return Observable<Todo[]> instead of subscribing internally and storing the result in a property?
Show answer
Returning the Observable lets each caller control when the request runs, combine or cancel it with RxJS operators, and bind it in templates. Subscribing inside the service hides errors, makes cancellation hard, and couples the service to one usage pattern.