4

i'm migrating from Http to HttpClient I'm used to add some headers to my http requests like the following with :

import { RequestOptions, Request, RequestMethod, Headers } from '@angular/http';


this.pass = btoa(cuid + ': ');
this.pass = "Basic " + this.pass;
this.header = new Headers();
this.header.set("Authorization", this.pass);
let options = new RequestOptions({
  headers: this.header
});

return this.http.post(myServiceUrl, {}, options)

Now when migrating to httpClient , i ve tried this :

import {HttpClient, HttpHeaders} from '@angular/common/http';

    const header = new HttpHeaders();
    const pass = 'Basic ' + btoa(cuid + ': ');
    header.set('Authorization', pass);
    const options =  ({
      headers: header
    });
    return this.httpClient.post(myServiceUrl, {}, options);

but as you can see ivent find the equivalent of RequestOptions , and the whole treatment failed to add the same headers.

Suggestions??

firasKoubaa
  • 6,439
  • 25
  • 79
  • 148

4 Answers4

14

The HttpClient.post method has the following signature:

post(url: string, body: any | null, options: OptionsType)

Where the OptionsType is the following (equivalent to RequestOptions)

{
  headers?: HttpHeaders | { [header: string]: string | string[] };
  observe?: "body";
  params?: HttpParams | { [param: string]: string | string[] };
  reportProgress?: boolean;
  responseType: "arraybuffer";
  withCredentials?: boolean;
};

From there you can assign you header or params, like:

const options = {
  headers: new HttpHeaders().append('key', 'value'),
  params: new HttpParams().append('key', 'value')
}


this.httpClient.post(url, {}, options)

You could also take a look to this question

J. Pichardo
  • 3,077
  • 21
  • 37
3

According to https://angular.io/guide/deprecations RequestOptions was replaced by HttpRequest

0

The http client equivalent should be:

const headers = new HttpParams().set('Authorization', pass);
return this.httpClient.post(myServiceUrl, {}, {headers: headers});
Mike Tung
  • 4,735
  • 1
  • 17
  • 24
0

I have done this before by making a method in my service of getHeaders(token):

  getHeaders(token) {
    return new HttpHeaders().set('Authorization', `Bearer ${token}`);
  }

Then when making requests just append this to the request like so:

this.http.post(url, body, this.getHeaders(token));

There is also the HttpInterceptor to look into that can automate this for requests, here is an article for this: https://www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/

I have done this using Firebase Auth for my tokens like this. Here is the token.interceptor.ts file:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  afAuth: any;

  constructor(
    private inj: Injector
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.afAuth = this.inj.get(AngularFireAuth);

    return this.getToken().pipe(
      switchMap(token => {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${token}`
          }
        });

        return next.handle(request);
      })
    );
  }

  getToken() {
    return Observable.fromPromise(this.afAuth.auth.currentUser.getIdToken());
  }
}

Then you need to provide this to your top level app.module like so:

{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }

What this does here is set the Authorization token for every HTTP request that gets handled automatically so you do not have to await a token before making requests. Keep in mind this is very specific to Firebase Auth as that's what is giving me the JWT token. Hope this can be of help!

Nicholas Pesa
  • 2,156
  • 2
  • 24
  • 45