Adding http headers in Angular 6

2020-02-13 08:08发布

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})
      }

7条回答
贼婆χ
2楼-- · 2020-02-13 08:10

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

查看更多
虎瘦雄心在
3楼-- · 2020-02-13 08:13

Try below code that might help you.

let headers = new HttpHeaders().set('Accept': 'application/json').set('zumo-api-version': '2.0.0')
查看更多
We Are One
4楼-- · 2020-02-13 08:16

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});
查看更多
SAY GOODBYE
5楼-- · 2020-02-13 08:23

Angular 6 format:

let headers = new HttpHeaders({
    'Accept': 'application/json',
    'zumo-api-version': '2.0.0'
});
查看更多
Evening l夕情丶
6楼-- · 2020-02-13 08:27

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
查看更多
淡お忘
7楼-- · 2020-02-13 08:34

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');
查看更多
登录 后发表回答