我正在尝试通过在 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 替换。
我没有替换标题,而是如何添加自定义标题
,我尝试了这样的操作:
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/