Search code examples
angulartypescriptangular-http

Angular 8 http.get bind a certain property only


Is there a way for angular http.get to deserialize a json object without the need of the root object?

json:

{
        "jsonprop" : [
            {
                "id" : 1,
                "name" : "testName"
            },
            {
                "id" : 2,
                "name" : "testName2"
            }
        ]
}

models:

export interface Jsonprop {
    id: number;
    name: string;
}

export interface RootObject {
    jsonprop: Jsonprop[];
}

http method: (working but this is not what i wanted)

getJsonProp(searchText: string): Observable<RootObject> {
    return this.http.get<RootObject>('apiurl');            
}

What I wanted to do instead is :

getJsonProp(searchText: string): Observable<Jsonprop[]> {
    return this.http.get<Jsonprop[]>('apiurl');            
}

Is there a way for me to do this?


Solution

  • You can use the map() operator from RxJS. For eg:

    return this.http.get<RootObject>('apiurl').pipe(
       map(response) => {
          return response.jsonprop;
       })
    );