Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a put request in angular2 using http?

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.

like image 868
Bhushan Gadekar Avatar asked Jul 23 '16 06:07

Bhushan Gadekar


People also ask

How do I send a HTTP PUT request?

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' });

What is put request in HTTP?

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.

Does Put require a request body?

So yes, a PUT request, technically, strictly, has to have a body.

How do you use Put method?

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.


2 Answers

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

like image 122
Ankit Singh Avatar answered Sep 23 '22 06:09

Ankit Singh


    //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....
like image 35
vishal Avatar answered Sep 23 '22 06:09

vishal