Using HttpClient to Fetch Data
Using HttpClient to Fetch Data
HttpClient is Angular's official HTTP client for talking to backends. It supports typed responses, error handling, and interceptors.
Set up the provider
Use the provideHttpClient function in your app configuration so the service is available:
import { provideHttpClient } from '@angular/common/http';
providers: [provideHttpClient()]
Inject and request
Inject HttpClient in the service and call get:
@Injectable({ providedIn: 'root' })
export class PostService {
private url = 'https://api.example.com/posts';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get<Post[]>(this.url);
}
}
The angle-bracket generic tells TypeScript what shape the response has, and HttpClient maps JSON to that type for you.
Observables and the async pipe
HTTP methods return RxJS Observables. A component stores the observable, and the template uses the async pipe to unwrap the value:
posts$ = this.posts.getPosts();
<li *ngFor="let post of posts$ | async">
{{ post.title }}
</li>
The async pipe subscribes for you and unsubscribes when the component is destroyed.
Handling errors
Catch failures with catchError inside the observable pipeline:
this.http.get<User>(this.url).pipe(
catchError(() => of(null))
);
Other HTTP verbs
post, put, patch, and delete follow the same pattern. post typically takes a request body:
this.http.post<Comment>('/comments', { text });
Whatever verb you use, the response flows back as a typed Observable.
Key Points
- provideHttpClient enables the HTTP support.
- Inject HttpClient and call typed request methods.
- HTTP responses are RxJS Observables.
- The async pipe auto-subscribes in templates.
- Handle failures with catchError and default values.