10

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.

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

2 Answers2

29

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

Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
  • 2
    you need to return JSON string from your service to make `res.json()` work, if not returning anything then you don't need `.map(res => res.json());` – Ankit Singh Aug 03 '16 at 11:15
  • 7
    @Ankit Singh Observables are lazy so you need to subscribe on them to make the request execute even if you don't want to handle the response. – user2171669 Mar 08 '17 at 18:52
  • 1
    @user2171669 You should have your comment as an answer! – Zarepheth Jul 31 '17 at 22:12
  • 1
    Why do they `JSON.stringify()` the body? Is that necessary/best practice? – cs_pupil Sep 21 '17 at 17:20
  • 1
    With version 4 you don't have to JSON.stringify() in fact that can create an error. Just add the object to the body and Angular does the rest. – Frank Cannon Jan 10 '18 at 14:18
  • also, if someone is asking itself about, they do not subscribe itself _but_ does UNsubscribe: https://stackoverflow.com/a/35043309/2079428 – netalex Jun 12 '18 at 07:52
1
    //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....
vishal
  • 11
  • 1