Html 如何编辑和删除项目?

Html 如何编辑和删除项目?,html,typescript,angular,Html,Typescript,Angular,我正在尝试构建自己的客户机-服务器应用程序。我已经建立了一个简单的html框架,并使用练习中的一些方法向服务器添加项目。到目前为止还没有数据库资料。我从服务类获得了添加项目的方法: addItem(name:string, price:number, successCallback, errorCallback) { this.http.post('/item', JSON.stringify({name: name, price: price}), {headers: this.

我正在尝试构建自己的客户机-服务器应用程序。我已经建立了一个简单的html框架,并使用练习中的一些方法向服务器添加项目。到目前为止还没有数据库资料。我从服务类获得了添加项目的方法:

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

下一个合乎逻辑的步骤是删除/编辑项目,但是这个示例没有涵盖这一点,尽管它可能相当简单,但我无法找出或者找到另一个适合的示例。我希望这里有人能帮我。这主要是我正在努力解决的http问题。。我想

您可以为此实施以下方法:

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) => {
    (...)
  });
}
否则,我不会利用回调进入
addItem
方法,而是利用可观察的对象。

试试这些-

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() }]
            }
        });
}
然后根据需要在你想要的地方订阅这些