javascript - 如何以 Angular 将自定义 header 添加到httpRequest

标签 javascript node.js angular typescript rxjs

我正在尝试通过在 headers 中传递一些来发出 http get() 请求,现在我将像这样替换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();<=====
  }

}

当我像这样替换标题时:

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

默认 header 值(即 Content-Type : application/json)将被上述 header 替换。

enter image description here 我没有替换标题,而是如何添加自定义标题,我尝试了这样的操作:

  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新手,有什么帮助吗?

最佳答案

您应该像这样将 header 添加到您的获取请求中。另外,由于 HttpHeaders 是不可变对象(immutable对象),因此您必须重新分配 header 对象

  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();
  }

关于javascript - 如何以 Angular 将自定义 header 添加到httpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56766716/

相关文章:

javascript - 我如何获得一个按钮来调用一个 JS 脚本,该脚本删除文本并将其替换为网格中的新文本?

javascript - Socket.io 不从客户端向服务器发送数据

javascript - 使用 Angular 检测对 iframe 的点击

javascript - 另一个 javascript 库上的 Angular 2 templateURL 功能

angular - 当 url 不可用时如何设置后备 (assets/i18n/en.json) (ngx-translate/http-loader)

javascript - Jquery 移动和鼠标悬停事件

javascript - 使用 Angularjs 通过下拉菜单启用/禁用按钮

javascript - 按名称搜索用户的最佳方法是什么?

node.js - 导入不适用于 "module": "ESNEXT" in tsconfig. json

node.js - 远程事件套接字的 Freeswitch ACL 配置