本文介绍了Angular:将Http的RequestOptions与HttpClient一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 Http 迁移到 HttpClient 我习惯于在http请求中添加一些标头,如下所示:
i'm migrating from Http to HttpClientI'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
)
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)
您还可以查看此问题
这篇关于Angular:将Http的RequestOptions与HttpClient一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!