How to inject HttpClient in static method or custom class?

后端 未结 4 1452
别那么骄傲
别那么骄傲 2021-02-04 02:24

I\'d like to use angular HttpClient in static method or class (in class it can\'t be defined as constructor parameter).

I tried something like:



        
4条回答
  •  孤街浪徒
    2021-02-04 03:18

    You can also skip the injector if you don't have one. That means doing the 'injecting' yourself. I don't recommend doing this. If you really want to use a static method (in favor of a proper service), pass all the needed stuff.

    I'm not sure if this isn't already obvious but any HTTP interceptor will be missing from this httpClient pipeline, since there's no way of resolving them.

    import { HttpClient, HttpXhrBackend } from '@angular/common/http';
    
    const httpClient = new HttpClient(new HttpXhrBackend({ build: () => new XMLHttpRequest() }));
    httpClient.get('test').subscribe(r => console.log(r));
    

    or using your own created injector (if you don't like passing ctor args):

    const injector = Injector.create({
        providers: [
            { provide: HttpClient, deps: [HttpHandler] },
            { provide: HttpHandler, useValue: new HttpXhrBackend({ build: () => new XMLHttpRequest }) },
        ],
    });
    const httpClient: HttpClient = injector.get(HttpClient);
    httpClient.get('test').subscribe(r => console.log(r));
    

提交回复
热议问题