Lee Maan
Lee Maan

Reputation: 719

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!

Upvotes: 0

Views: 2491

Answers (2)

Todarmal
Todarmal

Reputation: 306

Use this code for getting the status.

Updated on [15/02/19] :


getOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json;charset=UTF-8',
    "authToken": this.token // contains the authToken as parameter in request header 
                            // of http.get method for authorisation.
  })
};

// For getting the whole response of the request including status code etc.
getOptions['observe'] = 'response';


return this.http.get(url, getOptions)
         .pipe(
           catchError(this.handleError)
         )
         .subscribe(res => {
             console.log(res);
           },
           err => {console.log(err)} );

Above updated code will result in giving the whole response

Upvotes: 1

Justin Reusnow
Justin Reusnow

Reputation: 290

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.

Upvotes: 4

Related Questions