Stop Repeating HttpClient Code in Angular
In this article
If you find yourself copying and pasting the same HttpClient calls, error handling, and loading flags across your Angular components, you are not alone. This guide shows you how to wrap those repetitive patterns into a reusable service layer, cutting boilerplate and making your code easier to maintain. You will learn a practical, step-by-step approach that works with Angular's dependency injection and modern RxJS practices.
What You'll Need
- An Angular project (version 12 or later recommended, but the concepts apply to older versions too).
- Basic familiarity with Angular services, dependency injection, and RxJS observables.
- Angular CLI installed (optional, but helpful for generating files).
Step-by-Step
- Create a generic HTTP service. Generate a service that wraps the Angular HttpClient. This service will hold the common logic for GET, POST, PUT, DELETE, and error handling. Use the Angular CLI:
ng generate service core/http. This gives you a clean base to build on. - Inject HttpClient. In the new service, inject Angular's HttpClient via the constructor. Also inject Angular's ErrorHandler or a custom logging service if you have one. This keeps all HTTP interactions in one place.
- Add a generic GET method. Write a method like
get<T>(url: string, options?: any): Observable<T>. Inside, callthis.http.get<T>(url, options)and pipe it through acatchErroroperator. This method will be reused by all feature services. - Add a generic POST method. Similarly, create
post<T>(url: string, body: any, options?: any): Observable<T>. Usethis.http.post<T>(url, body, options)with the same error handling pipe. Repeat for PUT and DELETE as needed. - Handle errors centrally. In the catchError block, log the error (using your logging service or console.error) and rethrow a user-friendly error message. For example, map to a custom Error object or just return
throwError(() => new Error('Something went wrong')). This removes the need to write error handling in every component. - Create feature-specific services. For each domain (e.g., UserService, ProductService), inject your generic HTTP service instead of HttpClient. In these services, define methods that call the generic service with the specific endpoint URLs. For instance,
getUsers() { return this.http.get<User[]>('/api/users'); }. - Use the feature services in components. Inject the feature service into your component's constructor. Call the service method and subscribe to the observable. Because error handling is already in the generic service, your component code becomes simple: just assign the result to a property.
- Add a loading indicator (optional but common). Create a simple loading service or use a BehaviorSubject in the generic service to track pending requests. Increment a counter when a request starts and decrement when it completes. Expose an observable that components can subscribe to for showing a spinner.
- Consider caching (optional). For GET requests that don't change often, you can add a simple in-memory cache in the generic service. Use a Map to store responses by URL and return cached data if available. This reduces duplicate calls.
Common Mistakes
- Not using generics. If your generic service methods return
Observable<any>, you lose type safety. Always use generics like<T>to preserve the response type. - Forgetting to unsubscribe. Even with a service layer, subscriptions in components can cause memory leaks. Use the
asyncpipe in templates or manually unsubscribe inngOnDestroy. - Overcomplicating the error handler. Trying to handle every possible error scenario inside the generic service can make it rigid. Keep it simple: log and rethrow, and let specific services or components handle special cases if needed.
- Putting business logic in the generic service. The generic service should only handle HTTP mechanics. Don't add domain-specific transformations there—keep those in feature services.
- Ignoring HTTP interceptors. If you need to add auth tokens or log requests, use Angular interceptors instead of cluttering your service. Interceptors are the right place for cross-cutting concerns.
Tips
- Use the async pipe. In templates, use
user$ | asyncinstead of subscribing in the component. This automatically handles unsubscription and makes your code cleaner. - Define a consistent API response wrapper. If your backend returns a standard envelope like
{ data: ... }, you can unwrap it in the generic service so components get the data directly. - Use environment variables for base URLs. Store your API base URL in
environment.tsand inject it into the service. This makes it easy to switch between dev and production. - Keep your generic service small. It should have only a handful of methods (get, post, put, delete). If you find yourself adding many parameters, consider separate methods for special cases.
- Write unit tests for the generic service. Use Angular's HttpClientTestingModule to mock requests. This ensures your error handling and URL building work correctly.
Troubleshooting
Problem: The generic service methods are not being called; components still use HttpClient directly.
Solution: Ensure you are injecting the feature service, not HttpClient, in your components. Double-check that the feature service is provided in the module or component (using providedIn: 'root' is best).
Problem: Errors are not being caught in the generic service.
Solution: Make sure you are using the catchError operator inside the pipe() method, and that you are returning a new observable with throwError. Also verify that the generic service is the one making the HTTP call, not the feature service.
Problem: The loading indicator never turns off.
Solution: Check that you decrement the counter in both success and error cases. Use the finalize operator to ensure cleanup happens regardless of the outcome.
Problem: TypeScript complains about the generic type in the service.
Solution: Make sure you are using <T> in both the method signature and the HttpClient call. For example: get<T>(url: string): Observable<T> { return this.http.get<T>(url).pipe(...) }.
Frequently Asked Questions
Q: Can I use this pattern with Angular's new signal-based APIs?
A: Yes. You can wrap your service methods to return signals using toSignal() from '@angular/core/rxjs-interop'. The service layer remains the same; only the consumption in components changes.
Q: How do I handle different base URLs for different services?
A: You can pass the full URL to the generic service methods, or you can have the generic service accept a base URL in its constructor and create multiple instances with different configs. The simplest is to pass the full URL from the feature service.
Q: Should I put all HTTP calls in one service?
A: No. The generic service is for common logic, but you should have separate feature services for different domains. This keeps your code organized and maintainable.
Q: How do I add authentication headers?
A: Use an HTTP interceptor. It will automatically add headers to all requests, so your generic service doesn't need to know about auth.
Q: Is it okay to have the generic service return the full HttpResponse?
A: Yes, if you need headers or status codes. Use observe: 'response' in the HttpClient call and return Observable<HttpResponse<T>>.
Q: Can I use this pattern with Angular's HttpClient in standalone components?
A: Absolutely. Standalone components can inject services directly, and the generic service can be provided in the root. The pattern works the same.