How to inject HttpClient in static method or custom class?

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

    Passing the need service/object as a parameter helps a lot. In addition, it helps testing and code "readability". This following solution works with any type of object you are trying to inject. And, at least, you inject it where/when needed. The calling object is responsible for injecting the needed object.

    export class SomeNotInjectableService {
      static doSomething(injected: any) {
        httpClient = injected as HttpClient;
        if(httpClient) {
           httpClient.get(...);
         }
      }
    }
    

    then in your calling component or service, use it like this

      ...
      export class MyService/*or MyComponent*/{
          constructor(private http: HttpClient){}
          doTheThing(){
              SomeNotInjectableService.doSomething(this.http)/*...subscribe()*/;
          }
      }
    

提交回复
热议问题