简体   繁体   English

将Angular 6与HttpClient一起使用时如何切换到Fetch而不是XHR

[英]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. 我已经接触了角度4和6一段时间了,我一直在进行服务以在其中使用HTTP调用。 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 ? 默认情况下,使用XHR哪一个要如何获取?

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. HttpClientHttpClient使用的内容被视为实现细节 ,如果在后台使用XHR或fetch ,则不必关心您。 It's currently using XHR, but that could change any time and you'd not even know it. 它目前正在使用XHR,但是这种情况随时可能发生变化,您甚至都不知道。


Still, to answer your question: if you really want to use fetch in your code, then the easiest thing is to just... use fetch ? 不过,要回答您的问题:如果您确实要在代码中使用fetch ,那么最简单的方法就是...使用fetch Do not use HttpClient at all. 完全不要使用HttpClient

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 ). 替代方法是重新实现整个HttpClient (喜欢!),然后提供自定义的FetchHttpClient fetch的实现(例如FetchHttpClient )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM