我想使用ReflectiveInjector解析Http而不是通过在构造函数中注入。
以下是我的代码
import { ReflectiveInjector } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
private http;
constructor()
{
let injector = ReflectiveInjector.resolveAndCreate([
(<any>HttpClientModule).decorators[0].args[0].providers
]);
this.http = injector.get(HttpClient);
console.log(this.http)
}
当我使用ng服务时它工作正常,但是当我构建项目时它会抛出错误,无法读取属性&#39; 0&#39;未定义的。
注意:我正在开发Angular 5项目。
答案 0 :(得分:0)
您需要列出注射器中的所有提供商,例如 HttpModule
:
let injector = ReflectiveInjector.resolveAndCreate([
{provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
BrowserXhr,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
XHRBackend,
{provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy},
])
另见https://github.com/angular/angular/blob/master/packages/http/src/http_module.ts#L46-L55
HttpClientModule
的提供者可在https://github.com/angular/angular/blob/c8a1a14b87e5907458e8e87021e47f9796cb3257/packages/common/http/src/module.ts#L119-L132