Angular - inject in other way than constructor?

徘徊边缘 提交于 2019-12-06 14:08:47

Yes and no.

You can use the Injector, but the best way is to inject it into the service:

constructor(private injector: Injector) {
        let httpService: Http = this.injector.get(Http);
}

More about Injector can be found here: https://angular.io/api/core/Injector

Here is also usable link, as @DBosley mentioned: https://angular.io/guide/dependency-injection#appendix-working-with-injectors-directly

You can do this within Angular's DI using factory providers:

injectFields(dependency: SomeDependency) {
  let service = new FieldInjectedService();
  service.dependency = dependency;
  return service;
}

...

providers: [
  { provide: FieldInjectedService, useFactory: injectFields, deps: [SomeDependency] },
  ...
]

Here the FieldInjectedService doesn't have any constructor parameters, but must have its dependency property set to be any use. The downside, of course, is that nothing here requires you to set those fields, so you could easily create an invalid instance of the service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!