Angular 2在构造函数外部注入依赖项

hak*_*ian 14 singleton dependency-injection typescript angular

我正在深入研究Angular 2中的DI.我正在使用泛型子类型实现一个REST-Client,用于具体的数据类型,如下所示:

class RESTClient<T>{
    constructor() {
        var inj =  ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
        this.http = inj.get(Http);
        this.conf = RESTConfiguration;
    }
}
class BookClient extends RESTClient<Book>{      
    constructor(){
        // since I dont want to inject the HTTP Providers here, I'm using a custom    injector in the super class
        super();
    }
}

class WriterClient extends RESTClient<Writer>{      
    ...
    ...
}
Run Code Online (Sandbox Code Playgroud)

据我所知,在超类REST-Service注入的所有RESTClient之间将共享一个http服务.

现在我希望有一个RESTConfiguration类:

@Injectable()
export class RESTConfiguration {
    get baseURL() {
     return this._baseURL;
    }

    set baseURL(value) {
        alert("sets value to"+value);
        this._baseURL = value;
    }

    private _baseURL;

}
Run Code Online (Sandbox Code Playgroud)

它应该在主应用程序中配置如下:

initializeApp(){
  this.restconf.baseURL = "http://localhost:3004/";
}
bootstrap(MyApp, [RESTConfiguration]).then();
Run Code Online (Sandbox Code Playgroud)

现在我不知道如何注入我的RESTConfiguration到RESTService类的一个单一实例,而不将它传递给,我想,以减少重复代码,并避免与打字稿仿制药的问题仍然争论少的构造.

在上面的例子中(第一个代码片段)我正在尝试使用我创建的ReflectiveInjector注入我的配置,它为我提供了我的配置的自定义实例.

我想了几个解决方案:

  1. 通过使用服务或某些静态类属性使一个可用,可以访问Apps"全局注入器"

  2. 在我的配置中实现额外的单例逻辑

  3. 找到一种方法在构造函数之外使用angular-native注入方法?

我的想法是否存在错误,或者我滥用DI框架?

ron*_*ler 24

这应该为这个问题提供解决方案,但在任何需要注入服务而不将其作为构造函数参数提供的情况下也有帮助.

我在另一篇文章中看到了这个答案: 存储注入器实例以用于组件

您可以在AppModule类中配置Angular Injector,然后在任何其他类中使用它(您可以从任何类访问AppModule的成员).

在AppModule中添加:

export class AppModule { 
  /**
     * Allows for retrieving singletons using `AppModule.injector.get(MyService)`
     * This is good to prevent injecting the service as constructor parameter.
     */
    static injector: Injector;
    constructor(injector: Injector) {
        AppModule.injector = injector;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的其他类中,您可以执行以下操作(对于此问题,使用Http替换MyService):

@Injectable()
export class MyClass{
    private myService;

    constructor(){
        this.myService = AppModule.injector.get(MyService);
    }
}
Run Code Online (Sandbox Code Playgroud)

这相当于使用:

constructor(private myService: MyService){}
Run Code Online (Sandbox Code Playgroud)

  • 在一群子类扩展自的超类中引用 AppModule 时,我遇到了循环依赖关系。 (5认同)