Search code examples
angularangular-httpclient

angular 4 HTTP Client casting type response


In my angular 4 project I am using HTTP Client, when I have a GET call the response is sometimes articulated so I have to do something like:

 this.loggedUser.name = response._embedded.agent.name

But in this case I have this error:

Property '_embedded' does not exist on type 'HttpResponse'

I resolve the problem with casting the response to any:

getLoggedUser(url) {
return this.http.get(url, {observe: 'response'})
.map((response) => <any>response);
}

So, Did I have to cast to any all the response? Is this considered good practice, or should I be doing something else?


Solution

  • The HttpResponse<T> class does not have any _embedded property indeed. That is why you get the compiler error, since Typescript statically typed your response to HttpResponse<Object> (the generic type argument is meant for the body property of the response).

    Casting the response to <any> seems like a feasible solution in this case, if you know to expect the _embedded prop there at any time. A null check might be a nice addition though.

    Here is the HttpResponse<T> typing for reference:

    /**
     * A full HTTP response, including a typed response body (which may be `null`
     * if one was not returned).
     *
     * `HttpResponse` is a `HttpEvent` available on the response event
     * stream.
     *
     * @experimental
     */
    export declare class HttpResponse<T> extends HttpResponseBase {
        /**
         * The response body, or `null` if one was not returned.
         */
        readonly body: T | null;
        /**
         * Construct a new `HttpResponse`.
         */
        constructor(init?: {
            body?: T | null;
            headers?: HttpHeaders;
            status?: number;
            statusText?: string;
            url?: string;
        });
        readonly type: HttpEventType.Response;
        clone(): HttpResponse<T>;
        clone(update: {
            headers?: HttpHeaders;
            status?: number;
            statusText?: string;
            url?: string;
        }): HttpResponse<T>;
        clone<V>(update: {
            body?: V | null;
            headers?: HttpHeaders;
            status?: number;
            statusText?: string;
            url?: string;
        }): HttpResponse<V>;
    }