我不太清楚为什么它不能像你try 的那样工作(可能是你创建注入器时遗漏了什么),但如果你使用"注入"注入器,它就会工作
如果查看抛出错误的源代码,您会发现它提到了请求的处理程序,在您的示例中它似乎为空.当HttpClient以"传统"方式提供时,angular可能会注册一些内部处理程序,但不是按照您的方式提供
// 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;
}
}
你的静态类/方法
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的例子: