我正在尝试通过在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
的新手,有帮助吗?
答案 0 :(得分:2)
您应该像这样将标头添加到您的get请求中。另外,由于HttpHeaders是不可变的对象,因此您必须像这样编写
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();
}
答案 1 :(得分:1)
我认为您忘记了在请求中添加标头对象
来自
AlarmManager
收件人
return this.http.get<ICourses[]>(apiUrl).toPromise();
答案 2 :(得分:0)
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
constructor(private _http: HttpClient) {
}
public getHeaders(): HttpHeaders {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this._auth.token}`
});
return headers;
}
public getData() {
const url = `https://stackoverflow.com/api/test`;
const body = { };
const options = { headers: this.getHeaders() };
return this._http.post<any>(url, body, options);
}