将依赖项注入类中

时间:2018-02-15 03:19:16

标签: angular angular5

我创建了一个需要服务的类:

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,
//...
],

1 个答案:

答案 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实例。

提示:如果您怀疑哪种参数方法总是需要查看方法签名