keepcalculator

06 Numbers and Powers

Angular Resources: Which API to Use for Data Fetching

Card No. 06·72343 · Updated · Standard formula, shown below

This guide explains how to fetch data in Angular using the built-in HttpClient and the modern resource() API introduced in Angular 19. You’ll learn which API to choose based on your needs, and how to implement each with clear, practical examples.

What You’ll Need

  • An Angular project (version 17+ for HttpClient, version 19+ for resource())
  • Basic knowledge of TypeScript and Angular components
  • A backend API endpoint (or a mock service like JSONPlaceholder for testing)

Step-by-Step

  1. Choose the right API. For most applications, use HttpClient from @angular/common/http. It’s stable, widely documented, and works with all Angular versions. If you’re on Angular 19+ and want a declarative, reactive way to handle async data with built-in loading and error states, consider the new resource() function.
  2. Set up HttpClient. Import HttpClientModule (or provideHttpClient() in standalone) in your app config. In app.config.ts (standalone) add provideHttpClient() to the providers array.
  3. Create a service. Generate a service using Angular CLI: ng generate service data. Inject HttpClient into the service constructor.
  4. Write a GET request. In your service, define a method that returns an Observable. Example: getUsers() { return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users'); }
  5. Subscribe in a component. Inject the service into your component, call the method, and subscribe to the Observable. Assign the result to a component property. Don’t forget to unsubscribe in ngOnDestroy (or use the async pipe).
  6. Handle errors. Use the catchError operator to handle HTTP errors. Return a fallback value or rethrow. Display a user-friendly message in the template.
  7. Use the resource() API (Angular 19+). In a component, define a resource: usersResource = resource({ loader: () => fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()) }); Then in the template, use usersResource.value() and usersResource.isLoading() to display data and loading state.
  8. Use the async pipe. In your component template, use users$ | async to automatically subscribe and unsubscribe. This is the recommended pattern for Observables.
  9. Add request options. For POST, PUT, DELETE, pass the appropriate options. For headers, use HttpHeaders. For query params, use HttpParams.

Common Mistakes

  • Forgetting to import HttpClientModule or provideHttpClient() – results in a null injector error.
  • Subscribing to an Observable without unsubscribing, causing memory leaks. Use the async pipe or manually unsubscribe.
  • Not handling errors – the app may crash silently. Always add a catchError.
  • Using resource() without a reactive request function – it won’t re-fetch when parameters change.
  • Mixing Observables and promises incorrectly – resource() expects a promise or observable, not both.

Tips

  • Use the async pipe in templates to avoid manual subscription management.
  • For complex data transformations, use RxJS operators like map, filter, and switchMap.
  • Use Angular’s built-in HttpInterceptor to add auth tokens or log requests globally.
  • For server-side state management, consider using Angular’s new httpResource() (experimental in v19) or third-party libraries like NgRx.
  • Always type your HTTP responses with interfaces to catch errors at compile time.

Troubleshooting

  1. Error: NullInjectorError: No provider for HttpClient. Ensure you’ve added provideHttpClient() in your app config or imported HttpClientModule in your module.
  2. Data not loading. Check the network tab in DevTools. Verify the API URL is correct and CORS is enabled on the server.
  3. Observable not emitting. Make sure you’ve subscribed to it. In templates, use the async pipe.
  4. resource() not updating. If you pass a static value to the request function, it won’t re-run. Use a signal that changes when you want to refetch.
  5. Type errors with JSON. Define interfaces for your data. If the API returns a different shape, use map to transform it.

Frequently Asked Questions

  1. Should I use HttpClient or resource()? For most apps, HttpClient is the safe choice. Use resource() if you’re on Angular 19+ and want a more declarative, signal-based approach with built-in loading states.
  2. Can I use fetch() instead of HttpClient? Yes, but HttpClient offers better integration with RxJS, interceptors, and testing. It’s recommended for most cases.
  3. How do I handle authentication? Use an HttpInterceptor to add an Authorization header to every request. Or pass headers in each request.
  4. How do I cancel a request? With HttpClient, you can unsubscribe from the Observable. With resource(), you can use an AbortController.
  5. What’s the difference between Observables and Promises? Observables are lazy, cancellable, and can emit multiple values. Promises are eager and emit one value. Angular’s HttpClient returns Observables.
  6. Can I use resource() with a POST request? Yes, but you’ll need to call the resource’s update() method or use a signal to trigger a refetch. It’s more common for GET requests.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →