User123
User123

Reputation: 833

HTTP get request headers not setting correctly in angular

I am trying to send http get request along with headers as below

    var headers = {}
    headers['x-email'] = 1;
    headers['x-from'] = 1577836800;
    headers['x-to'] = 1598659200;


return this.http.get<any>(environment.apiUrl+'/User/getTrips',{headers: new HttpHeaders(headers)})
      .subscribe(data => {
        if (data == undefined) {
          this.rowData = [];
          this.errorMsg = data['Error'];
        } else {
          this.rowData = data.slice(1);
          this.gridOptions.rowData = data;
          this.gridOptions.api.refreshCells({force : true});
        }

When i see in network console, i could not see any headers in the request and hence am getting empty api response.

Upvotes: 0

Views: 875

Answers (1)

Dalorzo
Dalorzo

Reputation: 20024

Try initializing the variable before using it.

  const httpHeaders: HttpHeaders = new HttpHeaders({
        'x-email': 1,
        'x-from': 1577836800
        'x-to': 1598659200
      });

and then

 this.http.get<any>(environment.apiUrl+'/User/getTrips',
    {headers: httpHeaders })//... code continues here

My initial thought is HttpHeaders class has a few subtleties since it is immutable. By changing the initialization this way we make sure it is using the correct type and that everything is properly initialized before invoking the http.get

btw this is not correct: *if data is undefined; there is no Error property

 if (data == undefined) {
          this.rowData = [];
          this.errorMsg = data['Error']; /* if data is undefined; there is no Error property*/
        } 

Upvotes: 1

Related Questions