首页 > 解决方案 > 如何以角度将自定义标头添加到httpRequest

问题描述

我正在尝试http get()通过传递一些请求来发出请求valuesheaders现在我正在替换headers这样的:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ICustomer} from 'src/app/models/app-models';

@Injectable({
  providedIn: 'root'
})
export class MyService {
private baseUrl = '....api url....';
public authKey = '....auth_key......';

  constructor(private http: HttpClient) { }

  public async AllCustomers(): Promise<ICustomer[]> {
   const apiUrl = `${this.baseUrl}/customers`;

   return this.http.get<ICustomer[]>(apiUrl ,
    {headers: new HttpHeaders({Authorization: this.authKey})}).toPromise();<=====
  }

}

当我像这样替换标题时:

headers: new HttpHeaders({Authorization: this.authKey})

默认标头值(即 Content-Type : application/json)将替换为上述标头。

在此处输入图像描述 我没有替换标题我该如何添加custom headers,而是这样尝试:

  public async AllCustomers(): Promise<ICustomer[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    const headers = new HttpHeaders();
    headers.append('Authorization', this.authKey);
    headers.append('x-Flatten', 'true');
    headers.append('Content-Type', 'application/json');

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

我的方法有什么问题,我是新手angular,有什么帮助吗?

标签: javascriptnode.jsangulartypescriptrxjs

解决方案


You should add header to your get request like this. Also since HttpHeaders is immutable object you have to reassign header object

  public async AllCustomers(): Promise<ICourses[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', this.authKey);
    headers = headers.append('x-Flatten', 'true');
    headers = headers.append('Content-Type', 'application/json');

    return this.http.get<ICourses[]>(apiUrl, {headers}).toPromise();
  }

推荐阅读