Angular-以除构造函数外的其他方式注入? [英] Angular - inject in other way than constructor?

查看:179
本文介绍了Angular-以除构造函数外的其他方式注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular中,我有一个通过constructor(...)注入的东西很少的服务.但是,该服务也在某个地方通过调用构造函数创建.因此,向参数添加依赖的其他服务将更改API.我想避免这种情况.

In Angular, I have a service that has few things injected through the constructor(...). However that service is also at some place created by calling the constructor. Therefore, adding another service it depends on to the parameters would change the API. I'd like to avoid that.

是否有一种方法可以在不将服务添加到构造函数参数的情况下将其注入到另一个服务中?例如.现场注入?

Is there a way to inject a service into another service without adding it to the constructor parameters? E.g. field injection?

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;

推荐答案

是,不是.

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

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);
}

有关喷油器的更多信息可以在这里找到: https://angular.io/api/core/Injector

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

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

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

这篇关于Angular-以除构造函数外的其他方式注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆