首页 > 解决方案 > 如何在 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;
        }));
    }
}

标签: angularobservable

解决方案


HttpHeaders.append(...)创建一个HttpHeaders添加了新标头的新对象,它不会改变您当前的HttpHeaders对象实例。

这应该可以解决您的问题:

this.headers = this.headers.append('Authorization', 'Bearer ' + this.appState.get('_a_token'));

请记住,标头是不可变的,这意味着对它们进行的任何修改都会返回一个新实例,它不会改变对象本身。


推荐阅读