Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : Using the equivalent of RequestOptions of Http with HttpClient

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

like image 387
firasKoubaa Avatar asked Dec 04 '22 20:12

firasKoubaa


1 Answers

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

like image 101
J. Pichardo Avatar answered Dec 28 '22 05:12

J. Pichardo