Advertisement
Beginner Angular, HTTP Client & Interceptors

How do you send data to a server using a POST request with Angular's HttpClient?

Short answer

You call the post method on HttpClient, passing the target URL and the data you want to send as the request body, which Angular automatically converts to JSON by default, and it returns an observable just like a GET request does.

Save Angular mock interview
Advertisement
AModel answer
You call the post method on HttpClient, passing the target URL and the data you want to send as the request body, which Angular automatically converts to JSON by default, and it returns an observable just like a GET request does.
createUser(user: User) {
  return this.http.post<User>('/api/users', user);
}

// Elsewhere
this.userService.createUser(newUser).subscribe((created) => console.log('Created', created));
Real-world example
A signup form sends the new user's details to the backend using a POST request through HttpClient, subscribing to the response to confirm the account was successfully created.
Likely follow-ups
  • How would you set custom headers, like a content type, on a POST request?
  • What happens to the subscription if the component is destroyed before the request completes?
Related topics