Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

How can I switch to Fetch instead of XHR when using angular 6 with HttpClient

I have been into angular 4 and 6 for some time now,and I have been making Services to use HTTP calls in it. something like this:

@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());
    }
}

Which by default using XHR how can I swith to fetch ?

Upvotes: 2

Views: 2006

Answers (2)

Matthieu Riegler
Matthieu Riegler

Reputation: 54753

Since Angular 16.1 angular provides a HttpBackend with a fetch implementation.

Just use withFetch() within provideHttpClient()

Upvotes: 2

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

Firstly, there's no reason to do so. What HttpClient uses under the hood is considered an implementation detail and it shouldn't concern you if it's using XHR or fetch under the hood. It's currently using XHR, but that could change any time and you'd not even know it.


Still, to answer your question: if you really want to use fetch in your code, then the easiest thing is to just... use fetch? Do not use HttpClient at all.

public get(url): any
{
    return fetch(`${this.apiUrl}${url}`, this.headers());
}

The alternative is to re-implement whole HttpClient (yikes!) and then provide your custom fetch-like implementation (eg. FetchHttpClient).

providers: [
  { provide: HttpClient, useClass: FetchHttpClient }
]

Upvotes: 3

Related Questions