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

查看:31
本文介绍了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-directly

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

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

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