如何在静态方法或自定义类中注入HttpClient? [英] How to inject HttpClient in static method or custom class?

查看:307
本文介绍了如何在静态方法或自定义类中注入HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在静态方法或类中使用有角HttpClient(在类中不能将其定义为构造函数参数).

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

我尝试过类似的事情:

export class SomeNotInjectableService {
  static doSomething() {
    const injector = Injector.create({
      providers: [{provide: HttpClient, deps:[]}]
    });
    const httpClient: HttpClient = injector.get(HttpClient);

    httpClient.request(...); // error Cannot read property 'handle' of undefined
  }
}

这是尝试以静态服务方法手动注入客户端.不起作用我很好奇如何执行此操作或如何以普通方法但不是组件的类来注入客户端.

this is a try of injecting manually the client in static service method. Doesn't work. I'm curious how to do this or how to inject the client in normal method but in a class which isn't a component.

推荐答案

我不确定为什么它不能按照您尝试的方式工作(创建注射器时可能会丢失某些东西),但是如果您使用注入式"注入器

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

如果您查看引发错误的源代码,则会看到它提到了请求的处理程序,在您的示例中似乎为null.当以传统"方式而不是您的方式提供HttpClient时,angular可能会注册一些内部处理程序.

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); });

解决方法:

app.module.ts

import {Injector} from '@angular/core';

export let InjectorInstance: Injector;

export class AppModule 
{
  constructor(private injector: Injector) 
  {
    InjectorInstance = this.injector;
  }
}

您的静态类/方法

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);

    httpClient.request(...)...
  }
}

Stackblitz上的示例: https://stackblitz.com/edit/angular-li8b37? file = app%2Fapp.component.ts

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

这篇关于如何在静态方法或自定义类中注入HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆