0

When I want to append headers to a standard get, post, put or delete request, I can easily pass it inside the options object:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

this.httpClient.get<any>(
  'http://myapi.com/endpoint',
  httpOptions
)

However, when I am using the request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>; method of HttpClient, I am unable to pass any headers in anywhere as it doesn't accept any other parameters. I need to make my request this way since I need to append a file object to the body. This is the way I make the call:

this.httpClient.request(
  new HttpRequest(
    'POST',
    'http://myapi.com/endpoint',
    formData, // contains file object
  )
);

Is there a way to work this around?

3
  • The headers go in the HttpRequest object itself angular.io/api/common/http/HttpRequest Commented Jul 28, 2018 at 9:21
  • @user184994 That property seems read-only. Commented Jul 28, 2018 at 9:31
  • 1
    You can set it in the constructor. I've added an example below for you Commented Jul 28, 2018 at 9:36

1 Answer 1

1

According to the docs, you can add the headers into the HttpRequest object itself, like so

new HttpRequest(
  'POST',
  'http://myapi.com/endpoint',
  formData, // contains file object
  {
    headers: myHeaders
  }
)
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.