Angular:在 HttpClient 中使用等效于 Http 的 RequestOptions [英] Angular : Using the equivalent of RequestOptions of Http with HttpClient
本文介绍了Angular:在 HttpClient 中使用等效于 Http 的 RequestOptions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 Http 迁移到 HttpClient我习惯于将一些 headers 添加到我的 http 请求中,如下所示:
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)
现在迁移到 httpClient 时,我试过这个:
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);
但是正如你所看到的,ivent 找到了 RequestOptions 的等效项,并且整个处理未能添加相同的标头.
but as you can see ivent find the equivalent of RequestOptions , and the whole treatment failed to add the same headers.
建议??
推荐答案
HttpClient.post
方法具有以下签名:
post(url: string, body: any | null, options: OptionsType)
其中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)
你也可以看看这个问题
这篇关于Angular:在 HttpClient 中使用等效于 Http 的 RequestOptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文