Angular : Using the equivalent of RequestOptions of Http with HttpClient
Asked Answered
L

4

5

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??

Lynwoodlynx answered 30/5, 2018 at 14:4 Comment(1)
HttpParams is the new version, imported from the same placeIntrastate
M
15

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

Musky answered 30/5, 2018 at 14:51 Comment(0)
P
3

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

Presence answered 6/11, 2019 at 22:0 Comment(0)
M
0

The http client equivalent should be:

const headers = new HttpParams().set('Authorization', pass);
return this.httpClient.post(myServiceUrl, {}, {headers: headers});
Monophonic answered 30/5, 2018 at 14:7 Comment(1)
Types of property 'headers' are incompatible. Type 'HttpParams' is not assignable to type 'HttpHeadersLynwoodlynx
E
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!

Erasmo answered 30/5, 2018 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.