Search code examples
observableangular-httpangular-httpclientangular-observable

How to access inside attributes of json response in Observable map


Can anyone guide me to get solved this.

I am trying to access inside property of json response inside map operator.

return this.http.get('http://localhost:3000/api/businesses', options)
  .map((response: Response) => response.json());

and this return the whole responce, but i nned to get business property of that responce.

My API endpoint returns json object like this

{
   sucesses:true,
   business:[
     {},
     {}
   ]
}

So I need to access this object and return only business array


Solution

  • By calling response.json() you get an object back that you can query.

    Considering your response, you should get an object with two properties, success and business. Therefore you can just map the observable and return that property instead.

    return this.http
      .get('http://localhost:3000/api/businesses', options)
      .map((response: Response) => response.json())
      .map((data: { success: boolean, business: any }) => data.business);
    

    This returns the property business of the json response.