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})
}
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');
Angular 6 format:
let headers = new HttpHeaders({
'Accept': 'application/json',
'zumo-api-version': '2.0.0'
});
The correct format to set the headers would be as shown below.
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
headers = headers.append('zumo-api-version', '2.0.0');
url -X GET --header 'Accept: application/json' --header 'zumo-api-version: 2.0.0' 'https://myurl/tables/stuff'
In the above request the name of the header keys is Accept & zumo-api-version , the text preceding the :
Headers are basically set as key/value pairs
In angular 6+
declaration zone:
httpOptionsNoAuth : any;
initialization:
constructor(){
this.httpOptionsNoAuth = {
headers: new HttpHeaders().set('No-Auth', 'true')
};
}
usage:
return this._http.get<any>(`${url}`, { headers: this.httpOptionsNoAuth.headers});
You're getting nothing in return because you're not subscribing to that event. add .subcribe
to that function where ever you're calling it eg
getStuff().subscribe(data=>{
console.log(data);
}
)
so the data
you're subscribing to contains all the response and everything you need to know about that call.
You can read more from here https://angular.io/guide/http
I have done it like this in my code
httpOptions={ headers: new HttpHeaders({ 'Content-Type': 'application/json'})};
this.httpOptions.headers = this.httpOptions.headers.append('Token', this.Token);
And then in my http.get call, I have done this:
return this.http.get<JSON>(this.API_ADDRESS+'/api/RemoveEmployee/'+id,this.httpOptions
Try below code that might help you.
let headers = new HttpHeaders().set('Accept': 'application/json').set('zumo-api-version': '2.0.0')