0

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?

4
  • Change like this .map((response) =>response.json()); then subscribe to get the value. Commented Sep 6, 2017 at 10:43
  • @Sreemat Property 'json' does not exist on type 'HttpResponse<Object>'. Commented Sep 6, 2017 at 10:46
  • Can you explain what is this {observe: 'response'} Commented Sep 6, 2017 at 10:50
  • to read full response: angular.io/guide/http#reading-the-full-response Commented Sep 6, 2017 at 10:52

1 Answer 1

2

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>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.