Angular - 以构造函数之外的其他方式注入?

时间:2017-07-20 21:41:17

标签: angular typescript angular2-services angular-services

在Angular中,我有一项通过constructor(...)注入的东西很少的服务。但是,该服务也位于通过调用构造函数创建的某个位置。因此,根据参数添加另一项服务会改变API。我想避免这种情况。

有没有办法将服务注入另一个服务而不将其添加到构造函数参数?例如。现场注射?

import {Inject, Injectable} from "@angular/core";
import {
    Http, Request, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers,
    RequestMethod
} from "@angular/http";

import {KeycloakService} from "./keycloak.service";
import {Observable} from 'rxjs/Observable';
import {EventBusService} from "../events/event-bus.service";
import {LoadingSomethingFinishedEvent, LoadingSomethingStartedEvent} from "../events/windup-event";

@Injectable()
export class WindupHttpService extends Http {
    constructor(
        _backend: ConnectionBackend,
        _defaultOptions: RequestOptions,
        private _keycloakService: KeycloakService,
        // ----- This is what I want to avoid. -----
        private _eventBus: EventBusService,
    ) {
        super(_backend, _defaultOptions);
    }

    // -------  This is what I am looking for ---------
    //@Inject()
    //private _eventBus: EventBusService;

2 个答案:

答案 0 :(得分:4)

您可以使用factory providers

在Angular的DI中执行此操作
injectFields(dependency: SomeDependency) {
  let service = new FieldInjectedService();
  service.dependency = dependency;
  return service;
}

...

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

此处FieldInjectedService没有任何构造函数参数,但必须将其dependency属性设置为任何用途。当然,缺点是无需设置这些字段,因此您可以轻松创建无效的服务实例。

答案 1 :(得分:3)

是和否。

您可以使用Injector,但最好的方法是将其注入服务:

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

有关注射器的更多信息,请访问: https://angular.io/api/core/Injector

这里也是可用的链接,正如@DBosley所提到的:https://angular.io/guide/dependency-injection#appendix-working-with-injectors-directly