Skip to content

Angular services, HTTP, routing and forms: basics

Components draw the screen; the rest of an Angular application lives in services, flows through dependency injection, arrives over HTTP as observables, and is organized by the router and collected by forms. This page covers those six topics at the level you need to build a working feature, using OrdersPortal, an invented order-management app, as the running example. Each section links to the in-depth feature page for when you need more.

The samples target Angular 22 (@angular/core 22.2.6, TypeScript 6.0.3, RxJS 7). They were compiled with ngc and run on Node.js 22: component samples through renderApplication() from @angular/platform-server, the HTTP sample through TestBed with HttpTestingController, and the RxJS sample as a plain script. Outputs are shown under each sample.

Topic Use it for
Services Logic and state that more than one component needs
Dependency injection Letting Angular create and share those objects
HTTP Calling a backend API with HttpClient
Observables Streams of values: requests, user input, timers
Routing Mapping URLs to components, with lazy loading
Forms Collecting and validating user input

A service is a class that holds logic or state that should not live in a component: API calls, a shopping cart, pricing rules, feature flags. Components stay focused on presentation and ask for the service instead of creating it, which makes both easier to test.

Angular 22 adds the @Service() decorator (stable since 22.0) as the shorthand for @Injectable({ providedIn: 'root' }): the class is provided in the root injector automatically, created on first use, shared across the app, and tree-shaken if nothing uses it. @Service supports only inject() for its own dependencies. Keep @Injectable when you need constructor injection, useClass or useValue style providers, or a non-root scope; on Angular 21 and earlier, @Injectable({ providedIn: 'root' }) is the way to write the same thing. The ng generate @angular/core:service schematic (22.1 and later) converts eligible classes.

cart-service.ts
import { InjectionToken, Service, inject } from '@angular/core';
export interface TaxPolicy { rate: number; }
export const TAX_POLICY = new InjectionToken<TaxPolicy>('TAX_POLICY', {
providedIn: 'root',
factory: () => ({ rate: 0.2 }),
});
@Service()
export class CartService {
private readonly tax = inject(TAX_POLICY);
private readonly lines: { sku: string; price: number; qty: number }[] = [];
add(sku: string, price: number, qty = 1): void {
this.lines.push({ sku, price, qty });
}
total(): number {
const net = this.lines.reduce((sum, l) => sum + l.price * l.qty, 0);
return Math.round(net * (1 + this.tax.rate) * 100) / 100;
}
}

The output of this service is shown in the next section, where two components use it.

Pitfalls:

  • new CartService() in a component. It bypasses DI, so the component gets a private copy that shares no state with the rest of the app and cannot be replaced by a fake in tests.
  • Business rules in components. A tax calculation inside a click handler cannot be reused by the checkout page or tested without rendering; move it to a service.
  • Unbounded state in root services. A root service lives as long as the app. Caches in it need a size limit or an eviction rule.

Dependency injection (DI) means a class declares what it needs and an injector supplies it. In current Angular you ask with inject(Token) in a field initializer, constructor or factory; constructor parameters still work for @Injectable classes. A token is a class or an InjectionToken for non-class values such as configuration.

Injectors form a tree. The root (environment) injector holds providedIn: 'root' and @Service classes and anything in bootstrapApplication’s providers. Routes can have their own providers, and each component can declare providers that create new instances for that component and its children. Lookup starts at the requesting component and walks up, so a nearer provider overrides a farther one. That is how one subtree can use a different configuration.

// checkout.ts: a component-level provider overrides the tax policy for one subtree
import { Component, inject } from '@angular/core';
import { CartService, TAX_POLICY } from './cart-service';
@Component({
selector: 'app-us-checkout',
providers: [{ provide: TAX_POLICY, useValue: { rate: 0.07 } }, CartService],
template: `<p>US checkout total: {{ cart.total() }}</p>`,
})
export class UsCheckout {
protected readonly cart = inject(CartService);
constructor() { this.cart.add('SKU-42', 10, 2); }
}
@Component({
selector: 'app-root',
imports: [UsCheckout],
template: `<p>Root total: {{ cart.total() }}</p><app-us-checkout />`,
})
export class Shop {
protected readonly cart = inject(CartService);
constructor() {
this.cart.add('SKU-42', 10, 2);
console.log('same root instance:', this.cart === inject(CartService));
}
}

Output:

same root instance: true
<p>Root total: 24</p>
<p>US checkout total: 21.4</p>

Pitfalls:

  • Calling inject() outside an injection context. It works in field initializers, constructors, factories and provider functions, not in a click handler or setTimeout callback. Inject in a field and use the field later.
  • Accidental second instances. Listing a root service in a component’s providers creates a separate instance for that subtree, as the sample shows on purpose. If you see state “disappear”, look for a stray provider.
  • Strings as tokens. Use InjectionToken<T> so the value is typed and cannot collide with another library’s key.

HttpClient from @angular/common/http makes HTTP requests and returns observables. It is injectable by default in Angular 21 and later; call provideHttpClient() in app.config.ts when you need to add features such as withInterceptors([...]). It uses the browser fetch API by default (withFetch() is deprecated in 22 because it is now redundant; withXhr() switches back to XMLHttpRequest for upload progress events).

Requests are cold: nothing is sent until something subscribes, and each subscription sends a new request. Pass query parameters with HttpParams or the params option rather than string concatenation, type the response with a generic, and handle failures in the stream with RxJS operators. For read-only data that should become a signal, httpResource() wraps a request in a resource with value(), isLoading() and error() signals.

orders-api.ts
import { Service, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, catchError, map, of, retry } from 'rxjs';
export interface OrderSummary { id: number; customer: string; total: number; }
@Service()
export class OrdersApi {
private readonly http = inject(HttpClient);
search(customer: string): Observable<OrderSummary[]> {
const params = new HttpParams().set('customer', customer);
return this.http.get<OrderSummary[]>('https://api.example.test/orders', { params }).pipe(
retry(1),
map((orders) => orders.filter((o) => o.total > 0)),
catchError(() => of([])),
);
}
}

A test with provideHttpClientTesting() shows that no request leaves until subscribe(), what URL is sent, and what happens after two failures (the original plus one retry):

// orders-api.spec.ts (run as a script with TestBed on the server platform)
const api = TestBed.inject(OrdersApi);
const backend = TestBed.inject(HttpTestingController);
const request$ = api.search('Harbor Bikes');
console.log('requests before subscribe:', backend.match(() => true).length);
request$.subscribe((orders) => console.log('orders:', JSON.stringify(orders)));
const req = backend.expectOne((r) => r.url === 'https://api.example.test/orders');
console.log(req.request.method, req.request.urlWithParams);
req.flush([{ id: 1001, customer: 'Harbor Bikes', total: 249.5 }, { id: 1003, customer: 'Harbor Bikes', total: 0 }]);
api.search('Maple Cafe').subscribe((orders) => console.log('after two failures:', JSON.stringify(orders)));
backend.expectOne(() => true).flush('down', { status: 503, statusText: 'Service Unavailable' });
backend.expectOne(() => true).flush('down', { status: 503, statusText: 'Service Unavailable' });
backend.verify();

Output:

requests before subscribe: 0
GET https://api.example.test/orders?customer=Harbor%20Bikes
orders: [{"id":1001,"customer":"Harbor Bikes","total":249.5}]
after two failures: []

Pitfalls:

  • Never subscribing. A service method that calls this.http.get(...) and discards the result sends nothing. Return the observable and subscribe in the caller, the async pipe or toSignal().
  • Subscribing twice. Two async pipes on the same request observable send two requests. Use toSignal() once, or shareReplay(1) deliberately.
  • Swallowing errors silently. catchError(() => of([])) is fine for a search box, but a checkout call must surface the failure to the user and to logging.

An observable (from RxJS, which Angular depends on) is a stream that can emit zero, one or many values over time, then complete or error. Unlike a promise it is lazy, cancellable (unsubscribe) and composable with operators: map and filter transform values, debounceTime waits for a pause, distinctUntilChanged drops repeats, and switchMap maps each value to an inner observable and cancels the previous one, which is exactly what a type-ahead search needs.

Angular uses observables for HTTP, router events and reactive form value changes. For state shown in templates, signals are now the primary tool; toSignal() and toObservable() from @angular/core/rxjs-interop convert between the two, and takeUntilDestroyed() ends a subscription when the component is destroyed.

// order-search.ts: run with Node.js 22 after compiling (RxJS 7)
import { Subject, debounceTime, distinctUntilChanged, filter, map, switchMap, timer } from 'rxjs';
// Stand-in for OrdersApi.search(): answers after 50 ms.
const searchOrders = (term: string) => timer(50).pipe(map(() => [`${term.toUpperCase()}-1001`]));
const searchBox = new Subject<string>();
searchBox.pipe(
map((text) => text.trim()),
debounceTime(300), // wait for typing to pause
filter((term) => term.length >= 3),
distinctUntilChanged(), // "harb " trims to "harb": no new search
switchMap((term) => searchOrders(term)), // cancel the previous request
).subscribe((results) => console.log('results:', results));
const type = (text: string, at: number) =>
setTimeout(() => { console.log(`typed "${text}" at ${at} ms`); searchBox.next(text); }, at);
type('h', 0);
type('har', 100);
type('harb', 200);
type('harb ', 600);
type('maple', 1000);
setTimeout(() => searchBox.complete(), 1500);

Output:

typed "h" at 0 ms
typed "har" at 100 ms
typed "harb" at 200 ms
results: [ 'HARB-1001' ]
typed "harb " at 600 ms
typed "maple" at 1000 ms
results: [ 'MAPLE-1001' ]

Pitfalls:

  • Manual subscriptions without cleanup. A subscribe() in a component keeps running after the component is destroyed. Pipe through takeUntilDestroyed() or let the template subscribe.
  • mergeMap for searches. It keeps every request alive, so a slow early response can overwrite a newer one. Use switchMap when only the latest matters.
  • Nesting subscribes. A subscribe() inside another subscribe() loses cancellation and error handling; compose with switchMap, concatMap or forkJoin instead.

The Angular router maps URL paths to components so the app can navigate without full page loads. You define a Routes array, register it with provideRouter(routes) in app.config.ts, render the matched component in <router-outlet />, and link with routerLink. :id segments are route parameters; withComponentInputBinding() passes them straight into component inputs of the same name. loadComponent and loadChildren lazy-load code on first visit, title sets the document title, redirectTo redirects, and a final ** route catches unknown URLs.

Routes are matched in order, first match wins, which is why the wildcard goes last. Guards (canActivate, canMatch) and resolvers run around navigation and have their own pages.

// app.routes.ts and shell
import { Component, input } from '@angular/core';
import { Routes, RouterLink, RouterOutlet } from '@angular/router';
@Component({ selector: 'app-order-list', imports: [RouterLink], template: `<a routerLink="/orders/1001">Order 1001</a>` })
export class OrderList {}
@Component({ selector: 'app-order-detail', template: `<h2>Order {{ id() }}</h2>` })
export class OrderDetail {
readonly id = input.required<string>(); // filled from the :id route parameter
}
@Component({ selector: 'app-not-found', template: `<h2>Page not found</h2>` })
export class NotFound {}
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'orders' },
{ path: 'orders', component: OrderList, title: 'Orders' },
{ path: 'orders/:id', component: OrderDetail, title: 'Order details' },
{ path: 'reports', loadComponent: () => import('./reports').then((m) => m.Reports) },
{ path: '**', component: NotFound },
];
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
template: `<nav><a routerLink="/orders">Orders</a></nav><router-outlet />`,
})
export class Shell {}
// app.config.ts: providers: [provideRouter(routes, withComponentInputBinding())]

Rendering four URLs on the server gave the document title and the outlet content for each:

/ -> title "Orders": <app-order-list><a routerlink="/orders/1001" href="/orders/1001">Order 1001</a></app-order-list>
/orders/1001 -> title "Order details": <app-order-detail><h2>Order 1001</h2></app-order-detail>
/reports -> title "": <app-reports><h2>Reports</h2></app-reports>
/nope -> title "": <app-not-found><h2>Page not found</h2></app-not-found>

Pitfalls:

  • Wildcard first. { path: '**' } placed early swallows every route after it.
  • Missing pathMatch: 'full' on an empty-path redirect. With the default prefix matching, '' matches every URL and the redirect loops or hides other routes.
  • Reading snapshot in a reused component. Navigating from /orders/1001 to /orders/1002 reuses OrderDetail, so a value read once from route.snapshot goes stale. Input binding or paramMap observables update.

Angular has three form systems in @angular/forms. Template-driven forms (FormsModule, [(ngModel)]) build the model implicitly from directives and suit small forms. Reactive forms (ReactiveFormsModule, FormGroup, FormControl) build an explicit, typed model in the class with synchronous access to value and validity, and suit larger forms and dynamic structures. Signal Forms (@angular/forms/signals, Angular 21 and later, stable from 22) wrap a signal holding your data model in a FieldTree, bind inputs with [formField], and declare validation in one schema function.

All three track value, validity, errors, and touched and dirty state, and all three should be read through the form API rather than the DOM.

// return-request.ts: the same rules in reactive forms and Signal Forms
import { signal } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { email, form, min, required } from '@angular/forms/signals';
// Reactive forms: the model lives in FormGroup/FormControl objects.
const returnForm = new FormGroup({
email: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.email] }),
quantity: new FormControl(1, { nonNullable: true, validators: [Validators.min(1)] }),
});
returnForm.setValue({ email: 'not-an-email', quantity: 0 });
console.log('reactive valid:', returnForm.valid);
console.log('reactive errors:', JSON.stringify(returnForm.controls.email.errors), JSON.stringify(returnForm.controls.quantity.errors));
// Signal Forms: the model is a signal, validation is a schema function.
// form() needs an injection context: a component field initializer, or TestBed.runInInjectionContext in a test.
const model = signal({ email: '', quantity: 1 });
const returnRequest = form(model, (path) => {
required(path.email);
email(path.email);
min(path.quantity, 1);
});
returnRequest.email().value.set('buyer@example.test');
console.log('signal form valid:', returnRequest().valid());
console.log('model updated:', JSON.stringify(model()));
// Template: <input type="email" [formField]="returnRequest.email" /> with FormField in imports

Output:

reactive valid: false
reactive errors: {"email":true} {"min":{"min":1,"actual":0}}
signal form valid: true
model updated: {"email":"buyer@example.test","quantity":1}

Pitfalls:

  • Reading values from the DOM. document.getElementById('email').value skips validation state; use form.value, form.valid or the field state signals.
  • Mixing systems on one form. Do not put [(ngModel)] on a control that also has formControlName; pick one system per form.
  • Trusting client validation. Validators improve the experience; the API must validate again.
  • Put shared logic and state in a @Service (or @Injectable({ providedIn: 'root' }) before 22); override with component or route providers only when a subtree genuinely needs a different instance.
  • Fetch with HttpClient in a service; expose results to templates as signals with toSignal() or httpResource(), and use RxJS operators where timing matters (search, polling, retries).
  • Route by feature with lazy loading, and bind route parameters to inputs.
  • For forms: Signal Forms for new signal-based screens, reactive forms for existing code and complex dynamic forms, template-driven forms for very small forms.

What is the difference between @Service() and @Injectable({ providedIn: 'root' })? Both give a tree-shakable root singleton. @Service (Angular 22) is the shorter form and only supports inject()-based dependencies and a factory option. @Injectable still covers constructor injection, useClass or useValue style configuration, and non-root scopes such as platform.

Why does an HttpClient call do nothing until you subscribe? HttpClient returns cold observables: the request is made per subscription. That allows composing, retrying and cancelling the request before it is sent, and unsubscribing cancels an in-flight request.

When would you use switchMap rather than concatMap? switchMap when only the latest result matters and older work can be cancelled, such as search-as-you-type or loading the item for the current route. concatMap when every item must be processed in order, such as saving a queue of edits.

How do route parameters reach a component? With withComponentInputBinding(), route params, query params and resolved data are bound to component inputs with matching names. Without it, inject ActivatedRoute and read paramMap as an observable so the value updates when the component is reused.

Senior scenario: OrdersPortal’s order detail page shows the previous order’s data for a moment and sometimes the wrong order after fast clicks. How do you fix it? The component is reused across /orders/:id navigations and each navigation starts a request without cancelling the previous one, so responses race. Drive loading from the route parameter as a stream or signal: bind id as an input and load with httpResource(() => '/api/orders/' + id()) or toObservable(id).pipe(switchMap(...)), so a new id cancels the old request. Show a loading state from isLoading() instead of stale data, and add a test that flushes responses out of order with HttpTestingController.