Angular:将Http的RequestOptions与HttpClient一起使用

编程入门 行业动态 更新时间:2024-10-28 19:30:50
本文介绍了Angular:将Http的RequestOptions与HttpClient一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从 Http 迁移到 HttpClient 我习惯于在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)

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一起使用

本文发布于:2023-11-14 13:14:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Http   Angular   HttpClient   RequestOptions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!