Angular : Using the equivalent of RequestOptions of Http with HttpClient

一世执手 提交于 2020-01-15 03:24:10

问题


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


回答1:


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




回答2:


The http client equivalent should be:

const headers = new HttpParams().set('Authorization', pass);
return this.httpClient.post(myServiceUrl, {}, {headers: headers});



回答3:


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!




回答4:


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



来源:https://stackoverflow.com/questions/50606752/angular-using-the-equivalent-of-requestoptions-of-http-with-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!