0
0
AngularHow-ToBeginner · 4 min read

How to Make PUT Request in Angular: Simple Guide

In Angular, you make a PUT request using the HttpClient service's put() method. You pass the URL and the data object you want to update, and subscribe to the observable to handle the response.
📐

Syntax

The put() method of Angular's HttpClient sends data to update a resource on the server. It requires the URL and the data object as parameters. You can also pass optional HTTP options like headers.

  • url: The API endpoint to update data.
  • body: The data object to send.
  • options: Optional settings like headers.

It returns an Observable you subscribe to for the response.

typescript
httpClient.put(url: string, body: any, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}, observe?: 'body', params?: HttpParams | {[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', withCredentials?: boolean }): Observable<any>
💻

Example

This example shows how to update a user's data by sending a PUT request to an API endpoint. It uses Angular's HttpClient inside a service and subscribes to the response to log success or error.

typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/users/1';

  constructor(private http: HttpClient) {}

  updateUser(userData: any): Observable<any> {
    return this.http.put(this.apiUrl, userData);
  }
}

// Usage in a component
import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-root',
  template: `<button (click)="updateUser()">Update User</button>`
})
export class AppComponent {
  constructor(private userService: UserService) {}

  updateUser() {
    const updatedData = { name: 'Jane Doe', email: 'jane@example.com' };
    this.userService.updateUser(updatedData).subscribe({
      next: response => console.log('User updated:', response),
      error: err => console.error('Update failed:', err)
    });
  }
}
Output
User updated: { id: 1, name: 'Jane Doe', email: 'jane@example.com' }
⚠️

Common Pitfalls

Common mistakes when making PUT requests in Angular include:

  • Not importing HttpClientModule in your app module, causing HttpClient to be undefined.
  • Forgetting to subscribe to the observable, so the request never executes.
  • Sending incorrect data format or missing required fields in the body.
  • Not handling errors, which can cause silent failures.

Always ensure your service is injected properly and you subscribe to the put() observable.

typescript
/* Wrong: No subscription, request won't run */
this.http.put(url, data);

/* Right: Subscribe to execute and handle response */
this.http.put(url, data).subscribe(response => {
  console.log('Success', response);
});
📊

Quick Reference

Remember these tips for PUT requests in Angular:

  • Import HttpClientModule in your app module.
  • Inject HttpClient in your service or component.
  • Use put(url, body) to send update data.
  • Always subscribe to the observable to trigger the request.
  • Handle errors with subscribe error callback.

Key Takeaways

Use Angular's HttpClient put() method with URL and data to make PUT requests.
Always subscribe to the put() observable to send the request and handle responses.
Import HttpClientModule in your app module to enable HttpClient.
Handle errors in the subscription to avoid silent failures.
Pass the correct data object matching the API's expected format.