1

This worked in Angular 4. What do I change for it to work in angular 5?

 getGreeting(): Observable<string> {
    let headers = new Headers({ 'Authorization': 'Bearer ' + this.authenticationService.token });

  //cant find requestoptions
  let options = new RequestOptions({ headers: headers });

    return this.http.
        get(Constant.ApiRoot + Constant.GreetingService, options).
        map((response: Response) => response.text());
}
punkouter
  • 5,170
  • 15
  • 71
  • 116

3 Answers3

5

The headers can be passed as HttpHeaders or Plain JSON object but it should be part of HttpOptions. You can find more about it on Angular's official documentation at https://angular.io/guide/http#adding-headers

const httpOptions = {
      headers: new HttpHeaders({      
        'Authorization': Bearer ' + this.authenticationService.token 
      })
    };
this.httpClientObj.get('url',httpOptions);
2

This is what I use with my HttpClient.post and .get

let headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'responseType': 'json'
        });

this.http.post("url", { SomeDate: data }, { headers: headers })
this.http.get("url", { headers: headers })
Zze
  • 18,229
  • 13
  • 85
  • 118
1

Here is the detailed answer to the question:

Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).

There is more than one way we can pass data into the headers. The syntax is different but all means the same.

// Option 1 
 const httpOptions = {
   headers: new HttpHeaders({
     'Authorization': 'my-auth-token',
     'ID': emp.UserID,
   })
 };


// Option 2

let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');    

let options = {headers:httpHeaders};


// Option 1
   return this.http.post(this.url + 'testMethod', body,httpOptions)

// Option 2
   return this.http.post(this.url + 'testMethod', body,options)

In the call you can find the field passed as a header as shown in the image below : enter image description here

Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)

  • Response to the preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access

  • Response for preflight does not have HTTP ok status.

Find my detailed answer at https://stackoverflow.com/a/52620468/3454221

Trilok Pathak
  • 2,931
  • 4
  • 28
  • 34