How to inject HttpClient in static method or custom class?

后端 未结 4 1458
别那么骄傲
别那么骄傲 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:22

    I'm not exactly sure why it does not work the way you tried (probably something missing when you create the injector), but it works if you use an 'injected' injector

    If you look at the source code throwing the error you see that it mentions handlers for the request, which seems to be null in your example. Maybe angular registers some internal handlers when the HttpClient is provided the 'traditional' way, but not the way you do it

    // Start with an Observable.of() the initial request, and run the handler (which
    // includes all interceptors) inside a concatMap(). This way, the handler runs
    // inside an Observable chain, which causes interceptors to be re-run on every
    // subscription (this also makes retries re-run the handler, including interceptors).
    
    var /** @type {?} */ events$ = rxjs_operator_concatMap.concatMap.call(rxjs_observable_of.of(req), function (req) { return _this.handler.handle(req); });
    

    Work around:

    app.module.ts

    import {Injector} from '@angular/core';
    
    export let InjectorInstance: Injector;
    
    export class AppModule 
    {
      constructor(private injector: Injector) 
      {
        InjectorInstance = this.injector;
      }
    }
    

    Your static class/method

    import {InjectorInstance} from './app.module';
    
    export class SomeNotInjectableService {
      static doSomething() 
      {
      /*  const injector = Injector.create({
          providers: [{provide: HttpClient, deps:[]}]
        });
        const httpClient: HttpClient = injector.get(HttpClient);
    */
        const httpClient =  InjectorInstance.get(HttpClient);
    
        httpClient.request(...)...
      }
    }
    

    Example on Stackblitz: https://stackblitz.com/edit/angular-li8b37?file=app%2Fapp.component.ts

提交回复
热议问题