【问题标题】:Error while using body.json() for parsing response from http.get()使用 body.json() 解析来自 http.get() 的响应时出错
【发布时间】:2020-05-28 18:04:09
【问题描述】:

尝试使用 body.json() 将数据分配给对象数组,但当它返回一个承诺时尝试了这个。但是浏览器抛出错误,告诉我 json() 不是函数。

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response: Response) => {
      response.json().then(
        (data) => {
          this.recServ.setRecipes(data)
        }
      );
    }
  )
}

【问题讨论】:

  • json()HttpClient 的新版本中不是必需的。你也没有承诺在这里打电话给then()。你可以直接做(response: Response) => { this.recServ.setRecipes(response) }
  • “响应”类型的参数不可分配给“配方[]”类型的参数。 “响应”类型缺少“配方 []”类型中的以下属性:长度、弹出、推送、连接和 26 个以上。ts(2345)...收到此错误
  • 尝试将response: Response 更改为response: Recipe[]response: any 或只是response
  • 解决了,非常感谢:D

标签: javascript angular promise observable httpmodule


【解决方案1】:

您实际上可以像这样替换它,此外,可以将响应分配给接口以对其进行严格类型化。

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response) => this.recServ.setRecipes(response)
  );
}

【讨论】:

    【解决方案2】:

    angular httpClient 已经为你做了 .json()

    【讨论】:

      【解决方案3】:

      下面的代码 sn-p 可以帮助你

        getRecipes() {
          this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
            (response: Response) => {
                  this.recServ.setRecipes(JSON.parse(JSON.stringify(response)));
            }
          )}
      

      【讨论】:

        猜你喜欢
        • 2013-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 1970-01-01
        相关资源
        最近更新 更多