javascript - 如何以角度将自定义标头添加到httpRequest
问题描述
我正在尝试http get()
通过传递一些请求来发出请求values
,headers
现在我正在替换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
,有什么帮助吗?
解决方案
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();
}
推荐阅读
- react-native - 我收到警告,无法在 React Native on Expo 中使用 FontAwesome
- php - 如果其中还有 {},如何通过 {} 拆分字符串?
- java - 数组未正确设置值
- apache-spark - 写入 hdfs 时,如何仅覆盖必要的文件夹?
- c# - 需要红色的 string.Format("{0:0.00;( 0.00;zero}", -100)) 输出
- python - 忽略 TensorFlow 日志记录警告
- android - 在 App Update/Reinstall Rollout Xamarin 上保留 SQLite db 数据
- r - 在 uptR 包中的 x 轴上显示数字
- git - `git commit --amend -C HEAD` 和 `git commit --amend --no-edit` 一样吗?
- entity-framework - System.InvalidOperationException 将 EntityFrameworkCore 从 2.1 更新到 2.2 以获取可为空的属性