typescript Angular:在 HttpClient 中使用等效于 Http 的 RequestOptions

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50606752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:27:12  来源:igfitidea点击:

Angular : Using the equivalent of RequestOptions of Http with HttpClient

angulartypescriptangular-httpangular-httpclient

提问by firasKoubaa

i'm migrating from Httpto HttpClientI'm used to add some headersto my http requests like the following with :

我正在从Http迁移到HttpClient我习惯于向我的 http 请求添加一些标头,如下所示:

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 :

现在迁移到 httpClient 时,我试过这个:

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.

但是正如您所看到的, ivent 找到了等效的RequestOptions,并且整个处理未能添加相同的标头。

Suggestions??

建议??

回答by J. Pichardo

The HttpClient.postmethod has the following signature:

HttpClient.post方法具有以下签名:

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

Where the OptionsTypeis the following (equivalent to RequestOptions)

其中OptionsType是以下(相当于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

你也可以看看这个问题

回答by Durid Ahmad

According to https://angular.io/guide/deprecationsRequestOptionswas replaced by HttpRequest

根据https://angular.io/guide/deprecationsRequestOptions被替换为HttpRequest

回答by Mike Tung

The http client equivalent should be:

等效的 http 客户端应该是:

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

回答by Nicholas Pesa

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

我以前通过在我的服务中创建一个方法来做到这一点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));

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/

还有 HttpInterceptor 可以自动处理请求,这里有一篇文章:https: //www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new- http拦截器/

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

我已经使用 Firebase Auth 为我的令牌完成了这样的操作。这是 token.interceptor.ts 文件:

@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:

然后你需要把它提供给你的顶级 app.module 像这样:

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

{ 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!

这里所做的是为每个自动处理的 HTTP 请求设置授权令牌,这样您就不必在发出请求之前等待令牌。请记住,这是 Firebase Auth 特有的,因为这就是给我 JWT 令牌的原因。希望这能有所帮助!