首页 > 解决方案 > 使用 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 如何获取?

标签: javascriptangularfetch

解决方案


首先,没有理由这样做。幕后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 }
]

推荐阅读