我创建了一个需要服务的类:
export class RepositoryManager {
//...
private http: ApplicationHttpClient;
constructor() {
const injector = Injector.create({providers: [{provide: ApplicationHttpClient, deps: []}]});
this.http = injector.get(ApplicationHttpClient);
}
//...
}
但是,ApplicationHttpClient
服务要求将HttpClient
传递给构造函数。
@Injectable()
export class ApplicationHttpClient {
//...
public constructor(public http: HttpClient) { }
//...
}
我试图将HttpClient
作为deps(RepositoryManager)传递:
constructor() {
const injector = Injector.create({providers: [{provide: ApplicationHttpClient, deps: [HttpClient]}]});
this.http = injector.get(ApplicationHttpClient);
}
但是,发生以下错误:
NullInjectorError:没有HttpClient的提供者!
[编辑]
//...
imports: [
HttpClientModule,
//...
],
providers: [
{
provide: ApplicationHttpClient,
useFactory: ApplicationHttpClientCreator,
deps: [HttpClient]
},
HttpClient,
//...
],
答案 0 :(得分:0)
首先,您应该在根HttpClientModule
中导入AppModule
。
之后,您有两个选项来创建自定义注入器:
constructor(parentInjector: Injector) {
const injector = Injector.create({
providers: [{ provide: ApplicationHttpClient, deps: [HttpClient] }],
parent: parentInjector
});
...
}
或
constructor(parentInjector: Injector) {
const injector = Injector.create(
[{ provide: ApplicationHttpClient, deps: [HttpClient] }],
parentInjector
);
...
}
现在DI系统应该能够通过父注入器获取HttpClient
实例。
提示:如果您怀疑哪种参数方法总是需要查看方法签名