angular - 如何在 Angular 6 的请求选项中添加标头?
问题描述
我正在尝试添加 requestoption 和标头,但它引发以下错误
src/app/pages/ldapp/ldapp.service.ts(72,5): error TS2322: Type 'HttpHeaders' is not assignable to type 'Headers'.
Property 'forEach' is missing in type 'HttpHeaders'.
src/app/pages/ldapp/ldapp.service.ts(74,31): error TS2345: Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
Types of property 'headers' are incompatible.
Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
Index signature is missing in type 'Headers'
以下是我的代码
import { map } from 'rxjs/operators';
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Injectable()
export class LDappService {
private headers: HttpHeaders;
constructor(){
this.headers = new HttpHeaders();
}
private addAuthorizationHeader = () => {
this.headers.delete('Authorization');
this.headers.append('Authorization', 'Bearer ' + this.appState.get('_a_token'));
}
getladderRequest(gcid, callId, protocol, epoch) {
this.addAuthorizationHeader();
const url = this.baseApiUrl
this.urlParams = new URLSearchParams();
this.urlParams.set('callID', callId);
this.urlParams.set('protocol', 'SIP');
if (gcid != "") {
this.urlParams.set('gcid', gcid);
}
this.urlParams.set('pkey', epoch);
this.requestOptions.search = this.urlParams;
this.requestOptions.headers = this.headers;
return this.http.get(url, this.requestOptions).pipe(map(
res => {
return res;
}));
}
}
解决方案
HttpHeaders.append(...)
创建一个HttpHeaders
添加了新标头的新对象,它不会改变您当前的HttpHeaders
对象实例。
这应该可以解决您的问题:
this.headers = this.headers.append('Authorization', 'Bearer ' + this.appState.get('_a_token'));
请记住,标头是不可变的,这意味着对它们进行的任何修改都会返回一个新实例,它不会改变对象本身。
推荐阅读
- java - 如何实现特定的类型转换器?
- reactjs - Redux Form 没有触发提交功能
- python - 无法在 Heroku 上运行 Flask Socket.io chatapp:进程以状态 4 退出
- python - 按字符串反向排序列表
- python - 按钮未显示在窗口中
- java - 第二个 JPanel 和 JTexField 看起来太局促了
- java - 一个程序中的多个 Elasticsearch 连接
- python - 如何处理 docker 容器中的 403 禁止错误?
- testing - JMeter如何连续运行两个并行线程集
- python-3.x - Python - 带有 if 的 for 循环