Sub topic 3
Putting HTTP Calls in a Data Service
The previous chapter registered HttpClient with provideHttpClient. This chapter is about where your code should use it. In Angular, the usual answer is a data service. A data service is an injectable class that owns all HTTP calls for one resource, such as todos, users or orders. Components ask the service for data and never touch HttpClient themselves.
This chapter assumes you know TypeScript interfaces and generics, Angular components and dependency injection, and how a standalone application is bootstrapped with an ApplicationConfig. It also assumes that provideHttpClient() is already in your providers.
Why a Service Instead of the Component
You can inject HttpClient straight into a component, and it will work. As an application grows, though, that approach causes problems:
| Concern | HTTP in components | HTTP in a data service |
|---|---|---|
| URL and payload shape | Repeated in every component that needs the data | Defined once |
| API changes | Every component must be edited | One file changes |
| Testing components | Must mock HTTP traffic | Swap in a fake service |
| Testing HTTP logic | Must render a component | Test the service alone |
| Reuse across features | Copy and paste | Inject the same service |
A service also gives you a clear boundary. Components deal with display state and user events. The service deals with endpoints, request options and response shapes. Interceptors, covered in a later chapter, deal with concerns that apply to every request, such as authentication.
A Minimal Data Service
Here is the smallest useful version of the service used throughout this tutorial. The next chapters build out its GET, POST, PUT and DELETE methods in detail.
// 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);
}
}The service has four parts that are worth looking at one at a time.
`@Injectable({ providedIn: 'root' })`
providedIn: 'root' registers the service with the application's root injector, so the whole app shares a single instance. It is also tree-shakable: if nothing injects TodoService, the bundler can drop it from the build. You do not need to add it to any providers array.
`inject(HttpClient)`
The inject() function asks the current injector for a dependency. Calling it in a field initializer is the style current Angular documentation uses. The equivalent constructor form still works:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class LegacyTodoService {
constructor(private readonly http: HttpClient) {}
}The two forms behave the same at runtime. inject() has some practical advantages. It works the same way in services, components, functional guards and functional interceptors. It keeps constructors free for real initialization logic. It also avoids long parameter lists when a subclass has to pass dependencies up to its parent class.
`private readonly`
Marking http as private keeps components from reaching through the service to make their own ad hoc requests. Marking it readonly stops anyone from reassigning it by accident.
Returning, not subscribing
getTodos() returns the Observable and does not call subscribe(). This is the most important design rule for a data service. HttpClient Observables are cold, which means no request is sent until someone subscribes, and every subscription sends a new request. If the service returns the Observable:
- The caller decides when the request runs.
- The caller can compose it with operators such as
map,switchMaporcatchError. - The caller controls cancellation. Unsubscribing aborts the in-flight request.
- Templates can consume it with the
asyncpipe ortoSignal, which subscribe and unsubscribe for you.
Configuring the Base URL
Hard-coding '/api/todos' is fine with a dev-server proxy. Real deployments often need different API hosts per environment, though. An InjectionToken lets you supply the base URL through dependency injection, which also makes it easy to override in tests.
// api-base-url.token.ts
import { InjectionToken } from '@angular/core';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL', {
providedIn: 'root',
factory: () => '/api'
});// todo.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { API_BASE_URL } from './api-base-url.token';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = `${inject(API_BASE_URL)}/todos`;
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl);
}
}// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { API_BASE_URL } from './api-base-url.token';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
{ provide: API_BASE_URL, useValue: 'https://api.example.com' }
]
};The token's factory supplies a default value, so the app runs even when nobody provides the token. The useValue entry in appConfig overrides that default.
Using the Service from a Component
The component injects the service and does nothing with HTTP itself. The chapter "Showing API Data in Components" covers rendering options in depth. The short version uses the async pipe:
// todo-list.component.ts
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo-list',
imports: [AsyncPipe],
template: `
<ul>
@for (todo of todos$ | async; track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
`
})
export class TodoListComponent {
private readonly todoService = inject(TodoService);
readonly todos$ = this.todoService.getTodos();
}Assigning todos$ does not send a request. The request goes out when the async pipe subscribes during rendering. When the component is destroyed, the pipe unsubscribes.
Common Errors
`NullInjectorError: No provider for HttpClient`
The message may show the class as _HttpClient. This error means provideHttpClient() is missing from the injector that resolved your service. Check these causes:
provideHttpClient()is not inappConfig.providers, orappConfigis not passed tobootstrapApplication.- A unit test sets up
TestBedwithoutprovideHttpClient(). The testing chapter shows the correct setup. - An NgModule-based library still imports the deprecated
HttpClientModulein one place while the app usesprovideHttpClientin another, which leads to confusing injector setups. Pick one approach.
`NG0203: inject() must be called from an injection context`
inject() only works while Angular is creating the class. That covers field initializers, the constructor, and factory functions. The error appears if you call it inside a method:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class BrokenService {
load() {
const http = inject(HttpClient); // throws NG0203 when load() is called
return http.get('/api/todos');
}
}Move the inject() call to a field.
Accidental multiple instances
If you also list a providedIn: 'root' service in a component's providers array, that component and its children get a new, separate instance. Usually this happens by accident. It matters when the service holds state, such as a cache, because each instance keeps its own copy. Remove the extra provider unless you want a separate instance.
Duplicate requests
Each subscription to an HttpClient Observable sends its own request. If a template uses todos$ | async in two places, the app makes two network calls. Subscribe once, for example with @if (todos$ | async; as todos), convert the Observable to a signal with toSignal, or share the result on purpose with shareReplay.
Nothing happens
If a method such as deleteTodo(id) is called but no request appears in the Network tab, nobody subscribed. Write this.todoService.deleteTodo(id).subscribe(), or compose the call into a stream that is subscribed.
Exercise
A teammate writes a TodoService method loadTodos(): void that subscribes to http.get<Todo[]>(...) and stores the result in this.todos. Name two specific problems this design causes for the components that use it.
Show answer
Components cannot tell when the data has arrived, because the method returns nothing they can subscribe to or await, so they may read an empty or stale field. They also cannot cancel the request or handle its errors themselves, and they cannot compose it with operators like switchMap. The method should return Observable<Todo[]> and leave subscription to the caller.
Exercise
Your service declares private readonly http = inject(HttpClient);, and the app throws "NullInjectorError: No provider for _HttpClient!" only in unit tests, not in the browser. What is the most likely cause and the fix?
Show answer
The TestBed configuration does not register HttpClient. The browser works because appConfig includes provideHttpClient(), but tests build their own injector. Add provideHttpClient() to the TestBed providers, plus provideHttpClientTesting() if you want to intercept requests.
Exercise
You need the service to call https://staging.example.com in a staging build and https://api.example.com in production, without editing TodoService. How do you set this up?
Show answer
Define an InjectionToken<string> such as APIBASEURL, inject it in the service to build the base URL, and provide a different value per environment in the application providers, for example { provide: APIBASEURL, useValue: environment.apiUrl }. Tests can override the same token.