How do I edit and delete items?

I’m trying to build my own client – server application. I’ve set up a simple html skeleton and used some of the methods from the exercises to add items to the server. No database stuff so far tho. I got this method for adding items, from the service class:

 addItem(name:string, price:number, successCallback, errorCallback) {
      this.http.post('/item', JSON.stringify({name: name, price: price}), {headers: this.headers}).subscribe((response) => {
        this.items.push(new Item(+response.text(), name, price));
        successCallback();
      }, (response) => {
        errorCallback();
      });
    }

The next logical step would be deleting / editing items, but the example did not cover this, and all though it’s probably fairly simple i can’t figure it out or find another example that fits. I was hoping someone here could help me out. it’s mainly the http stuff i struggle with.. i think.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You could implement the following methods for this: updateItem(id:string, obj:any) { this.http.put(`/item/${id}`, JSON.stringify(obj), { headers: this.headers }).subscribe((response) => { var itemIndexToUpdate = this.items.find((item => item.id===id)); this.items[itemIndexToUpdate] = obj; }, (response) => { (...) }); } deleteItem(id:string) { this.http.delete(`/item/${id}`, { headers: this.headers }).subscribe((response) => { var itemIndexToRemove = this.items.findIndex((item => item.id===id)); if (itemIndexToRemove != -1) { this.items.splice(itemIndexToRemove, 1); } }, (response) => { (...) }); } Otherwise I wouldn’t leverage callbacks into the addItem method but leverage rather observables.

Jason
Guest

try these – EditRequest(url,data) { this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token')) this.requestoptions = new RequestOptions({ method: RequestMethod.Put, url: url, headers: this.headers, body: JSON.stringify(data) }) return this.http.request(new Request(this.requestoptions)) .map((res: Response) => { if (res) { return [{ status: res.status, json: res.json() }] } }); } DeleteRequest(url,data) { this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token')) this.requestoptions = new RequestOptions({ method: RequestMethod.Delete, url: url, headers: this.headers, body: JSON.stringify(data) }) return this.http.request(new Request(this.requestoptions)) .map((res: Response) => { if (res) { return [{ status: res.status, json: res.json() }] } }); } and than subscribe these where… Read more »