将自定义属性添加到请求标题角6

时间:2018-11-26 11:18:32

标签: angular httprequest angular6

尝试将自定义属性添加到HttpHeader请求,但似乎未发送。

  getUserInfo(){
    this.headers.append('CustomerId', 'ad34e1b2'); 
    return this._http.get(this.baseUrl+"getInfo",{ headers:this.headers });
  }

2 个答案:

答案 0 :(得分:1)

如果检查post()模块的HttpClient方法参数,您将看到如下可接受的参数:

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

 /**
 * Construct a POST request which interprets the body as JSON and returns the full response.
 *
 * @return an `Observable` of the `HttpResponse` for the request, with a body type of `Object`.
 */
post(url: string, body: any | null, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe: 'response';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;

表示该函数接受urlbodyoptions作为主要的可接受参数。您可以通过创建一个接受标头名称和值的函数来指定自定义标头。如果是单个自定义标头,则是这样,如果是多个标头,则可以自由编写自己的函数版本。

private setHeaders(customHeader: string, value: string): HttpHeaders {
const headers: HttpHeaders = new HttpHeaders({
  customHeader: value,
});
return headers;
}

并且最近不要忘记导入这些库。

import { HttpClient, HttpHeaders } from '@angular/common/http';

答案 1 :(得分:0)

您需要导入新的HttpHeaders

import { HttpClient, HttpHeaders } from '@angular/common/http';

在您的函数中创建它的一个实例

let headers = new HttpHeaders();
 headers.append('CustomerId', 'ad34e1b2');

或创建多个可以添加的内容

let headers = new HttpHeaders(
{'abc':'22',
'abc2':'111',
'abc4':'444'}
);
相关问题