【问题标题】:How to make a put request in angular2 using http?如何使用http在angular2中发出请求?
【发布时间】:2016-11-27 02:29:47
【问题描述】:

我正在开发这个 angular2 应用程序,并且正在执行 CRUD 操作。

我有 http 用于发出 getpost 请求。

我现在想执行put 操作,但找不到任何相关内容。

任何输入?

谢谢。

【问题讨论】:

标签: typescript angular


【解决方案1】:

如果你已经熟悉POST,那么

POST 和 PUT 请求之间的唯一区别是 UT 而不是 OST, 它只是一个verb,至少用于前端。

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

记住 - Observables 可能是惰性的(例如:Angular 的Http 请求),因此即使您不想处理响应,您也需要订阅它们以使请求执行。 – @user2171669

【讨论】:

  • 您需要从您的服务返回 JSON 字符串以使 res.json() 工作,如果没有返回任何内容,那么您不需要 .map(res => res.json());
  • @Ankit Singh Observables 是惰性的,因此即使您不想处理响应,您也需要订阅它们以使请求执行。
  • @user2171669 你应该有你的评论作为答案!
  • 他们为什么要JSON.stringify()身体?这是必要的/最佳实践吗?
  • 使用第 4 版,您不必 JSON.stringify() 实际上会产生错误。只需将对象添加到正文中,其余的由 Angular 完成。
【解决方案2】:
    //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....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-02
    • 2017-11-28
    • 2017-03-12
    相关资源
    最近更新 更多