How do you make a basic GET request to a server using Angular's HttpClient?
Short answer
You inject the HttpClient service into your component or service, and call its get method with the target URL, which returns an observable that emits the response once the request completes successfully.
Advertisement
AModel answer
You inject the HttpClient service into your component or service, and call its get method with the target URL, which returns an observable that emits the response once the request completes successfully.
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
getUsers() {
return this.http.get<User[]>('/api/users');
}
// Elsewhere
this.userService.getUsers().subscribe((users) => console.log(users));Real-world example
A user list component fetches all users from a backend API using HttpClient's get method, subscribing to the resulting observable to display the data once it successfully arrives.
Likely follow-ups
- Why does HttpClient return an observable instead of a promise?
- What happens if you forget to subscribe to the observable returned by a get request?
Related topics