Search code examples
angularangular-httpclient

in Angular 4 HttpClient how can I receive status code?


To get data I am doing:

data = this.http.get(url, httpOptions);

But this is only returning the body. I need the entire response to get the status. I know this syntax:

data = this.http.get(url, {observe: 'response'});

But this is replacing my httpOpttions which will make me unauthenticated. I can't add another argument on GET like I can in POST. Please help!


Solution

  • The reason why you can't add a third parameter to your http.get is because it doesn't accept a third parameter. The observe "syntax" IS part of the httpOptions parameter, so all you need to do is merge what is in your httpOptions object with {observe: "response"}

    For example, if your httpOptions looks like:

    const httpOptions = {
      headers: {
        "Content-Type": "application/json"
      }
    }
    

    You can combine that with the observe object above like this:

    const httpOptions = {
      headers: {
        "Content-Type": "application/json"
      },
      observe: "response"
    }
    

    If you are accepting httpOptions as an argument (so you can't create a new one from scratch like in the previous example), you can just write the observe field directly on it:

    httpOptions.observe = "response"
    

    Either of these methods will preserve your current httpOptions object and add the observe: "response" field to it.

    EDIT

    For this method to work, you will need to "lie" to the compiler about observe's type to allow it to compile. You can do this by adding as any to the end of "response" in your httpOptions object:

    const httpOptions = {
      headers: {
        "Content-Type": "application/json"
      },
      observe: "response" as any
    }
    

    The reason this is needed is because TypeScript can't infer the type of your raw httpOptions object correctly (it wants "response" to be the literal "body"). Telling TypeScript to interpret "response" as any gets around this problem.