dependency-injection – 将类绑定到接口

前端之家收集整理的这篇文章主要介绍了dependency-injection – 将类绑定到接口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用typescript,我可以轻松地将类绑定到自己:
bootstrap(MyAppComponent,[MyClass]);

但是,我想将我的类绑定到一个接口,如下所示:

boostrap(MyAppComponent,[???]);

这样我可以按如下方式注入:

class MyAppComponent {
    constructor(my_class : IMyClass){
    }
};

这在Angular2中可能吗?如果是,我该如何指定绑定?

简而言之,问题是编译typescript时接口消失了。所以你必须使用带有字符串的@Inject。

或者还有另一种选择,如果你检查the last article of Victor Savkin 你可以在评论中找到它:

Some background. In TypeScript,interfaces are structural and are not retained at runtime. So you have to use ILoginService as follows:

constructor(@Inject("ILoginService") s:ILoginService).

You don’t have to use a string – any object can be passed in there. We actually provide an object called OpaqueToken that can be used for this purpose.

interface ILoginService { login(credentials);}
const ILoginService = new OpaqueToken("LoginService");

can be used like this:

constructor(@Inject(ILoginService) s:ILoginService).

猜你在找的Angularjs相关文章