Angular - HttpClient: Map Get method object result to array property

angular httpclient get example
angular 8 http get example
angular observable map
angular map json to object
angular map http response to object
angular map response to object
angular httpclient headers
angular 6 observable example

I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works.

Below is my sample code ..

// my service call ..
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Show} from '../models/show';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class MyService {

  constructor(private http: HttpClient ) { }


  findAllShows(): Observable<Show[]> {
    return this.http
      .get<Show[]>(`${someURL}/shows`)
  }
}

If the return is a JSON Object such as below this fails..

// Service API that FAILS ...
{
  "shows": [
    {
      "id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-13 15:54:47",
      "name": "Main Show1"
    },
    {
      "id": "456f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-14 15:54:47",
      "name": "Main Show2"
    },
    {
      "id": "789f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-17 15:54:47",
      "name": "Main Show3"
    }
  ]
}

Now this one works if I just return the Array

// Service API that Works ...
[
    {
      "id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-13 15:54:47",
      "name": "Main Show1"
    },
    {
      "id": "456f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-14 15:54:47",
      "name": "Main Show2"
    },
    {
     "id": "789f9165-80a2-41d8-997a-aecc0bfb2e22",
      "modified": "2017-08-17 15:54:47",
      "name": "Main Show3"
    }
  ]

How do I map the JSON object Observable into an Array Observable???

You can simply .map() your http call, which is an Observable, to return the data type that you want.

findAllShows(): Observable<Show[]> {
    return this.http
        .get(`${someURL}/shows`)
        .map(result=>result.shows)
}

Your httpClient.get() should return an Observable, which you have explicitly stated it thought Observable<Show[]>. You .map() is an operator that transform the observable into a new one.

More on .map() operator: http://reactivex.io/documentation/operators/map.html

Update:

For RXJS version 6 and above, simply use .pipe() to pipe the .map() operator:

findAllShows(): Observable<Show[]> {
    return this.http
        .get(`${someURL}/shows`)
        .pipe(map(result=>result.shows))
}

Angular HttpClient map observable array of objects, What is the simplest way to map each object of the result (Rxjs Observable) to an Angular HttpClient generic get method returns object instead Typed object it still contains all properties I expect this response object as array of my custom  I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works. Below is my sample code .. // my service call .. import { Injectable } from '@angular/core'; import [&hellip;]

Latest HttpClient which should be used instead of http has no map method. You should first import it by import { map } from 'rxjs/operators'; Then you should use it this way:

this.http.get(`${someURL}/shows`).pipe(
        map(res => res['shows'])
    )

HttpClient: Map Get method object result to array property , I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my  Hey thanks for confirming that. I realised afterwards that I was trying to do something like automapper in the .NET world i.e. if the JSON result had more fields than I wanted, I just thought the this.http.get<User[]> would map only the data from the JSON to my User array.

.map(res=> res['shows'] ) does the trick

Get data from a server, if the heroes array is not empty, the method below returns the highest // hero id + 1. Still in the HeroService , inject HttpClient into the constructor in a private property HttpClient.get() returns the body of the response as an untyped JSON object data out by processing the Observable result with the RxJS map() operator. Default value that returns new HttpClient is Object. It automatically calls response.json() internally. You can tell HttpClient what type the response will be, so: this.httpClient.get<Timeslot[]>() .map((timeSlots) => { where timeSlots's type will be Timeslot[] See more information about typecheking in new HttpClient

Thanks All, I was able to find solution by combining responses from @ Arun Redhu by providing a transfer object interface that the server sends back. Then solution provided by @CozyAzure by using the .map() to transform one Observable to the correct Observable Show[].

Full Solution below for those interested.

import {Observable} from 'rxjs/Observable';
import {Contact} from '../models/show';
import {environment} from '../../../environments/environment';
// Use the new improved HttpClient over the Http
// import {Http, Response} from '@angular/http'; 
import {HttpClient} from '@angular/common/http';

// Create a new transfer object to get data from server
interface ServerData {
  shows: Show[];
}

@Injectable()
export class ShowsService {

  constructor(private http: HttpClient ) { }

// want Observable of Show[]
  findAllShows(): Observable<Show[]> {  
    // Request as transfer object <ServerData>
    return this.http
      .get<ServerData>(`${apiURL}/shows`)
     // Map to the proper Observable I need 
      .map(res => <Show[]>res.shows); 

  }
}

All great now!!! Thanks . So depending on data returned I can either use directly or map to proper Observable I need.

HTTP Example with Observables • Angular, Consuming REST API data using HttpClient in Angular is the most common way return a observable with a array of objects that match the type “TodoModel”. use of HttpClient to call the REST API and get the data to bind to the view. levels like Class Decorator, Method Decorator or Property Decorator. To perform http GET request, HttpClient provides HttpClient.get method that accepts URL and options for parameter, header etc and returns an Observable instance. When we subscribe Observable then GET request is executed on the server. Find the syntax of HttpClient.get from Angular doc.

There are 2 approaches of doing this. You can use .map operator form the observable to map one type of observable into another and second approach includes just with the help of interface.

1st Approaches (with the help of .map)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

interface ItemsResponseObj {
    id: string,
    modified: string,
    name: string
}

interface ItemsResponse {
    shows: Array<ItemsResponseObj>;
}

@Injectable()
export class AppService {

    constructor(private http: HttpClient) { }

    getData(): Observable<ItemsResponseObj[]> {
        return this.http.get<ItemsResponse>('api/api-data.json')
            .map(res => res.shows);
    }

}

and in the 2nd approach with the help of wrapping interfaces

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

interface ItemsResponseObj {
    id: string,
    modified: string,
    name: string
}

interface ItemsResponse {
    shows: Array<ItemsResponseObj>;
}

@Injectable()
export class AppService {

    constructor(private http: HttpClient) { }

    getData(): Observable<ItemsResponse> {
        return this.http.get<ItemsResponse>('api/api-data.json')
    }

}

How to map REST API data using Decorator pattern in Angular 6, Angular - HttpClient: Map Get method object result to array property. I am calling an API that returns a JSON Object. I need just the value of the array to map to a  Then inject HttpClient service in constructor method after that you can hit the remote server via HTTP’s POST, GET, PUT and DELETE methods. HttpClient in Angular 8/9. HttpClient API service is used to make communication between front-end web apps with backend services. This communication is done over HTTP protocol.

Observables Array Operations, constructor(http: HttpClient) {. http.get('http://jsonplaceholder.typicode.com/users/'​) map will create a new array with the results of calling a provided function on every element in this array. In this example we used it to Now every object in our array has "Dr." prepended to the value of its name property. filter will create a​  Just like in the case of GET, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification such as PUT. The PUT method should only be used if we want to fully replace the value of a resource.

Angular HTTP Client - QuickStart Guide, This post will be a quick practical guide for the Angular HTTP Client module. they have some great properties (more about them in this post). are then mapping the response we got from Firebase into an array, using the lodash then the result of the call to get() will be an Observable<Object> instead. HttpClient was introduced after Angular v4.3 so if you have later version you can simply continue. Let’s get started! First, we will create a new Angular project using the latest version of Angular CLI.

Mapping JSON from API call to TypeScript classes, On past projects (without TypeScript), I've always just used the JSON objects //​ViewModel response = await fetch(apiString, { method: "GET" }); if(response.ok) this.items get away with somehow using the spread operator to map all the properties? (object: Z) => T) => { let client: HttpClient = HttpClient(this); const result  Other APIs may bury the data that you want within an object. You might have to dig that data out by processing the Observable result with the RxJS map() operator. Although not discussed here, there's an example of map() in the getHeroNo404() method included in the sample source code.

Comments
  • I tried and got error... Property 'shows' does not exist on type 'Response' .
  • @Netwobble No, do not type cast it to type Response. See my edit.
  • 'map' function is still not available for httpClient
  • @ArunRedhu httpClient.get() should return an Observable, which us explicitly stated throughObservable<Show[]>. The .map() is an operator that transform the observable into a new one.
  • get('') with no type parameter should return Observable<Object>. Try with .map(res => res['shows'])
  • Make sure to have "suppressImplicitAnyIndexErrors": true, in your tsconfig.json file to suppress error TS7015.
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
  • Yeah More info to why res.shows doesn't work but this works
  • lol, why <Show[]>? The .shows property in the map already has the wished type
  • I tried the above approach. I am getting the data in the service but not in the component. Can you show me how to call the service in the component?Thanks in advance
  • creating a new interface just to wrap the data, and then unwrap it is not the best approach