I am working on this angular2 application and I am doing CRUD operations.
I have http for making get
& post
requests.
I want to perform put
operation now but cannot find anything relevant.
Any inputs?
Thanks.
Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });
The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.
So yes, a PUT request, technically, strictly, has to have a body.
Use PUT when you want to modify a single resource which is already a part of resources collection. PUT overwrites the resource in its entirety. Use PATCH if request updates part of the resource. Use POST when you want to add a child resource under resources collection.
If you are already familiar with POST
, then
Only difference between POST and PUT request is literally UT
instead of OST
,
it's just a verb
, for front-end atleast.
Angular Docs (have to make it complicated)
// Update existing Hero
private put(hero: Hero) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let url = `${this.heroesUrl}/${hero.id}`;
return this.http
.put(url, JSON.stringify(hero), {headers: headers})
.map(res => res.json());
}
And remember - Observables can be lazy (eg: Angular's Http
request) so you need to subscribe on them to make the request execute even if you don't want to handle the response. – @user2171669
//For .map(res => res.json());
//solution is below..
private updateProduct(product: IProduct, options: RequestOptions): Observable {
const url = `${this.baseUrl}/${product.id}`;
let headers = new Headers();
headers.append('Content-Type', 'application/json')
return this._http.put(url, JSON.stringify(product), {headers: headers})
.map(() => product)
.do(data => console.log('updateProduct: ' + JSON.parse(JSON.stringify(data || null)) ))
.catch(this.handleError);
}
//But I am unable to update any record....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With