How to inject HttpClient in static method or custom class?

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

    base on Andrew answer. If you want to use interceptors in this this httpClient pipeline, add two redefined classes from angular repo http/src/interceptor.ts and http/src/module.ts:

    class HttpInterceptorHandler implements HttpHandler {
      constructor(private next: HttpHandler, private interceptor: HttpInterceptor) {}
    
      handle(req: HttpRequest): Observable> {
          return this.interceptor.intercept(req, this.next);
      }
    }
    class HttpInterceptingHandler implements HttpHandler {
      private chain: HttpHandler|null = null;
      private httpBackend:HttpHandler;
      constructor(private injector: Injector) {
          this.httpBackend = new HttpXhrBackend({ build: () => new XMLHttpRequest });
      }
    
      handle(req: HttpRequest): Observable> {
          if (this.chain === null) {
              const interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
              this.chain = interceptors.reduceRight((next, interceptor) => new HttpInterceptorHandler(next,interceptor),this.httpBackend);
          }
          return this.chain.handle(req);
        }
    }
    

    Interceptors need without @Injectable decorator:

    class HttpIntersept implements HttpInterceptor{
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
          console.log(req.urlWithParams);
          return next.handle(req)
      }
    }
    

    And like Andrew was say

    const injector = Injector.create({
    providers: [
        { provide: HTTP_INTERCEPTORS, useClass: HttpIntersept, multi: true, deps: []},
        { provide: HTTP_INTERCEPTORS, useClass: HttpIntersept2, multi: true, deps: []},
        { provide: HttpHandler, useClass:HttpInterceptingHandler,deps [Injector,HTTP_INTERCEPTORS]},
        { provide: HttpClient, deps: [HttpHandler] }
     ],
    });
    

提交回复
热议问题