Use HttpClient inside a service, return Observables, and keep components free of HTTP details. 1. Provide HttpClient (standalone apps) // app.config.ts export const appConfig: ApplicationConfig = { providers: [provideHttpClient(withInterceptors([authInterceptor]))] }; (For NgModule apps, the older approach was importing HttpClientModule.) 2. Create a typed service export interface Product { id: number; name: string; price: number; } @Injectable({ providedIn: 'root' }) export class ProductService { private readonly http = inject(HttpClient); private readonly baseUrl = environment.apiUrl + '/products'; getAll(page = 1): Observable<Product[]> { return this.http.get<Product[]>(this.baseUrl, { params: { page } }); } getById(id: number): Observable<Product> { return this.http.get<Product>(`${this.baseUrl}/${id}`); } create(product: Omit<Product, 'id'>): Observable<Product> { return this.http.post<Product>(this.baseUrl, product); } } 3. Add the token with an interceptor export const authInterceptor: HttpInterceptorFn = (req, next) => { const token = inject(AuthService).token(); return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req); }; 4. Use it in a component @Component({ selector: 'app-products', template: ` @if (products$ | async; as products) { @for (p of products; track p.id) { <div>{{ p.name }} - {{ p.price | currency:'INR' }}</div> } } @else { <p>Loading...</p> } `, imports: [AsyncPipe, CurrencyPipe] }) export class ProductsComponent { products$ = inject(ProductService).getAll().pipe( catchError(err => { console.error(err); return of([]); }) ); } Points worth mentioning: HttpClient observables are cold (each subscribe sends a request), the async pipe subscribes and unsubscribes automatically, errors should be handled centrally (interceptor) and locally where the UI needs it, and newer Angular versions also offer httpResource() and toSignal() for signal-based data loading.
Ravindra Wadile · · 0 likes