Search code examples
javascriptangularpromiseobservablehttpmodule

Error while using body.json() for parsing response from http.get()


Tried using body.json() to assign data to an array of object but as it returns a promise tried this. But browser throws error telling me json() is not a function.

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

Solution

  • You can actually replace it like this, Also, can assign response to an interface to strict-type it.

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