SGR*_*SGR 2 javascript node.js rxjs typescript angular
我试图做一个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();<=====
}
}
Run Code Online (Sandbox Code Playgroud)
当我像这样替换标题时:
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();
}
Run Code Online (Sandbox Code Playgroud)
我的方法有什么问题,我是新手angular,有什么帮助吗?
您应该像这样将标头添加到您的获取请求中。此外,由于 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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8294 次 |
| 最近记录: |