Search code examples
rxjsangular-httpclient

Map HttpClient response data while returning an HttpResponse


In my service I always convert the JSON to an actual class type using rxjs like so.

get(id: UUID): Observable<OrderDTO> {
    return this.http.get<OrderDTO>(`${this.baseUrl}/${id}`)
        .pipe(
            map(x => OrderDTO.fromJson(x))
        );
}

I now have a case where I want to do that, but also get the HTTP headers as well. So I'd add {observe: 'response'} to the get call and then return an Observable<HttpResponse<OrderDTO>>...except I can't figure out how to still do the appropriate map there. Can someone help me with that syntax please?


Solution

  • I think you will get a returned HttpResponse Object from the http call, you can map your desire HttpResponse properties and response body and return an array for example

    this.http.get<OrderDTO>(`${this.baseUrl}/${id}`)
            .pipe(
                map(resp => 
                    [resp.headers,resp.body])
            ).subscribe(([header,body])=>....);