Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding http headers in Angular 6

Can anyone tell me if this is the correct way to add headers to http requests in Angular 6?

When I make the call via SwaggerUI, I can see the headers should be:

url -X GET --header 'Accept: application/json' --header 'zumo-api-version: 2.0.0' 'https://myurl/tables/stuff'

so I have added the following:

let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('HttpHeader1', 'Accept:application/json');
headers = headers.append('HttpHeader2', 'zumo-api-version:2.0.0');

And then the call:

getStuff(){
    return this.http.get('https://myurl/tables/stuff', {headers})
  }

There is no failure but nothing is returned, and I know that there should be.

thanks

UPDATE

Have just noticed that the url in my call is actually https not http, would that make any difference?

getStuff(){
        return this.https.get('https://myurl/tables/stuff', {headers})
      }
like image 482
DarkW1nter Avatar asked Aug 23 '18 15:08

DarkW1nter


People also ask

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers.

Where are HTTP headers set?

In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name. In the Value box, type the custom HTTP header value.

Which of these options is correct for setting headers in Angular JS HTTP post?

To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults. headers. get = { 'My-Header' : 'value' } .

What is HTTP protocol in Angular?

What Is HttpClient? HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signature and return types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe it.


2 Answers

The correct way to set headers is

let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
headers = headers.append('zumo-api-version', '2.0.0');
like image 180
Sajeetharan Avatar answered Oct 06 '22 02:10

Sajeetharan


Angular 6 format:

let headers = new HttpHeaders({
    'Accept': 'application/json',
    'zumo-api-version': '2.0.0'
});
like image 25
Ayoub k Avatar answered Oct 06 '22 01:10

Ayoub k