javascript - 使用 Angular 6 和 HttpClient 时如何切换到 Fetch 而不是 XHR
问题描述
我已经进入 angular 4 和 6 一段时间了,我一直在制作服务以在其中使用 HTTP 调用。像这样的东西:
@Injectable()
export class ApiService
{
private apiUrl:string;
constructor(
private httpClient: HttpClient,
private config: ConfigService,
private cookieService: CookieService
)
{
this.apiUrl = this.config.get("apiEndpoint");
}
private headers() :any
{
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/json');
headers = headers.set('Authorization', 'Bearer '+this.cookieService.get("token"));
return headers;
}
public get(url): any
{
return this.httpClient.get(`${this.apiUrl}${url}`, this.headers());
}
public post(url, data = {}): any
{
return this.httpClient.post(`${this.apiUrl}${url}`, data, this.headers());
}
public put(url, data = {}): any
{
return this.httpClient.put(`${this.apiUrl}${url}`, data, this.headers());
}
public patch(url, data = {}): any
{
return this.httpClient.patch(`${this.apiUrl}${url}`, data, this.headers());
}
public delete(url, data = {}): any
{
return this.httpClient.delete(`${this.apiUrl}${url}`, this.headers());
}
}
默认情况下使用 XHR 如何获取?
解决方案
首先,没有理由这样做。幕后HttpClient
使用的东西被认为是实现细节,如果它使用 XHR 或幕后,它不应该让您担心fetch
。它目前正在使用 XHR,但这可能随时改变,你甚至都不知道。
不过,要回答你的问题:如果你真的想fetch
在你的代码中使用,那么最简单的事情就是......使用fetch
?根本不要使用HttpClient
。
public get(url): any
{
return fetch(`${this.apiUrl}${url}`, this.headers());
}
另一种方法是重新实现整体HttpClient
(哎呀!),然后提供您的类似自定义fetch
的实现(例如。FetchHttpClient
)。
providers: [
{ provide: HttpClient, useClass: FetchHttpClient }
]
推荐阅读
- python - 来自 python NoBrokersAvailable 的 Kafka 消费者
- concordion - Concordion 无法复制资源(突然)
- php - 自定义谷歌云自动翻译 json 请求说收到无效的 JSON 有效负载
- mysql - 加速 MySQL 空间查询(点在多边形查找)
- java - 将哈希图从活动传递到片段的问题
- sql - BigQuery 解析 URL 网址
- cypress - 在 Cypress 中配置环境变量
- php - 使用 mysql 数据创建谷歌图表
- c++ - 使用 cpprestsdk 时出现堆损坏异常
- c# - C# 从其他任何地方访问在运行时构建的数据表