当构造函数具有参数时,Angular 2中的依赖注入 [英] Dependency injection in Angular 2 when a constructor has arguments

查看:282
本文介绍了当构造函数具有参数时,Angular 2中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示模型的typescript类,我希望实例通过angular的 Http 服务与API通信。

I have a typescript class representing a model and I would like instances to communicate with an API via angular's Http service.

但是模型的构造函数在创建实例时需要参数。例如,一些非常简单的事情:

But the constructor of the model needs arguments when creating instances. For example something super simple:

class SomeModel{
    constructor(public id:number, public name:string, ){
    }

我想注入 Http service所以它可用于我的实例,但似乎这样做的规范方法是使用以下命令来构造构造函数:

I would like to inject the Http service so it is available to my instances, but it seems like the canonical way to do this commandeers the constructor with:

constructor(http:Http)

我一直在挖掘注射器 docs,但它有点稀疏,我没有发现任何有效的东西。有没有办法在不使用构造函数模式的情况下从DI系统获取对 Http 等服务的引用?

I've been digging through the Injector docs, but it's a little sparse and I haven't found anything that works. Is there a way to get a reference to a service like Http from the DI system without using the constructor pattern?

推荐答案

我设法使用角度4解决了同样的问题。首先,您创建了使用组件注入器的新注入器。它知道你的 SomeModel 类并传递 modelParams 作为 SomeModelParameters 上课。然后使用这个新创建的注入器来创建类实例。

I managed to solve the same problem using angular 4. First you create new injector that uses component injector. It knows about your SomeModel class and passes modelParams as instance of SomeModelParameters class. Then you use this newly created injector to create class instance.

@Injectable()
class SomeModel {
    constructor(http: Http, someModelParamters: SomeModelParameters) { }
}

export class MyComponent {
    constructor(injector: Injector) {
        const modelParams = new SomeModelParameters();
        const injectorWithModelParams = ReflectiveInjector.resolveAndCreate(
            [
                SomeModel,
                { provide: SomeModelParameters, useValue: modelParams }
            ],
            injector);
        this.someModel = injectorWithModelParams.resolveAndInstantiate([SomeModel]);
    }
}

这篇关于当构造函数具有参数时,Angular 2中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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